Rest Controller
We’ve defined a simple rest controller for demo purposes. By default, our Fitler can recognize any URL pattern so we don’t have to worry about mapping in this example. However, if we need the filter to be invoked only for specific URLs, then we need to specify that before which we will see in the next example.
Java
// Simple REST Controller for testing our Servlet Filter import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping ( "/api" ) public class ServletController { //Get-Request Mapping @GetMapping ( "/" ) public String hello(){ return "This is a sample API for testing Servlet Filter - Spring Boot!" ; } } |
Output:
Console Output:
Other ways we can use servlet filters involve –
- For a category of URL Patterns
- Multiple servlet filters chained with @Order annotation and many more.
Spring Boot – Servlet Filter
Spring boot Servlet Filter is a component used to intercept & manipulate HTTP requests and responses. Servlet filters help in performing pre-processing & post-processing tasks such as:
- Logging and Auditing: Logging operations can be performed by the servlet filter logging the request and response which assists in debugging and troubleshooting.
- Authentication and Authorization: Authentication and Authorization refer to the process of providing access and checking if a user has certain privilege permissions to access a resource
- Caching: Caching is a mechanism that allows us to store data temporarily for faster access in the future. It can be done by caching response in servlet filters.
- Routing: Servlet filters can also be used for routing responses to different controllers giving us more control over handling requests