Filter example in Spring Boot

In this article, we will see Filter example in Spring Boot and how to configure Filter. Also, we will see how to configure multiple filters. Let’s see some basic about Filter.

Filter example in Spring Boot

  • Filter is an interface available in javax.servlet package which use to perform filtering task on request to a resource (a servlet or static content), or on the response from a resource.
  • The filter will get invoked before Controller/endpoint classes.
  • We can also define multiple filters if needed.
  • We can define our custom filter implementing this interface. Since Filter interface contains three methods (has been defined below), our custom filter need to override these methods.

void init(FilterConfig filterConfig) throws ServletException – This method is invoked by container only one time. It tells this filter has been placed into service. If we have some problem inside this method or it throws ServletException other tasks will not perform.

void doFilter(ServletRequest servletRequest, ServletResponse ServletResponse, FilterChain filterChain) throws IOException, ServletException – This method is also invoked by container each time whenever the client sends request or server send a response. In this method, we can check our request is proper or not. Even if we want we can modify request and response data.

void destroy() – This one is also called by the container.

Real-time use of filter –  Suppose we want to allow some specific request URI, we can restrict by configuring a filter. We can also provide log information in init(), doFilter() method. We can also configure some security related stuff for example if you want to enable cross-origin resource sharing(CORS), we can configure inside doFilter() method. Apart from this if it needed we can customized request data in doFilter() method.

Let’s see an example –

Step 1 – Create a maven project and update the pom.xml as below.

Step 2 – Define below packages and classes.

Filter example in Spring Boot

 

Book.java

BookController.java

FirstFilter.java

SpringMainExample.java

Run the SpringMainExample.java and deploy the application.

Filter example in Spring Boot

In the above screenshot, we can see init() method has been invoked while tomcat start, still doFilter() method has not been invoked. Let’s hit below URI from postman which we have defined in the controller class.

http://localhost:9092/book/getbook

Filter example in Spring Boot

In console we have content of doFilter() method. Yes, doFiletr() has been invoked now. In fact, doFiletr() will always get invoked with each new request. I am going to two times the same request, see the console output.

2019-02-20 21:18:03.452 INFO 2628 — [ main] c.filter.mainexample.SpringMainExample : Starting SpringMainExample on anjali-PC with PID 2628 (C:\Users\anjali\springsecurity\FilterExample\target\classes started by anjali in C:\Users\anjali\springsecurity\FilterExample)
2019-02-20 21:18:03.452 INFO 2628 — [ main] c.filter.mainexample.SpringMainExample : No active profile set, falling back to default profiles: default
2019-02-20 21:18:04.860 INFO 2628 — [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]13e16fd: startup date [Wed Feb 20 21:18:04 IST 2019]; root of context hierarchy
2019-02-20 21:18:26.455 INFO 2628 — [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9092 (http)
2019-02-20 21:18:26.499 INFO 2628 — [ main] o.apache.catalina.core.StandardService : Starting service Tomcat

init() method has been get invoked
Filter name is firstFilter
ServletContext name [email protected]
init() method is ended
2019-02-20 21:18:27.736 INFO 2628 — [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]13e16fd: startup date [Wed Feb 20 21:18:04 IST 2019]; root of context hierarchy
2019-02-20 21:18:27.846 INFO 2628 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/book/getbook],methods=[GET]}” onto public com.filter.entity.Book com.filter.controller.BookController.getBook()
2019-02-20 21:18:27.846 INFO 2628 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/error]}” onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>>

……

2019-02-20 21:30:10.267 INFO 2628 — [nio-9092-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization started
2019-02-20 21:30:10.362 INFO 2628 — [nio-9092-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization completed in 95 ms
doFilter() method is invoked
Context path is
doFilter() method is ended
doFilter() method is invoked
Context path is
doFilter() method is ended

 

We can configure multiple filters and call them in a different sequence. We can use @Order annotation with filter and give the order how we want to invoke them. For example, we are going to define two more filters SecondFilter.java and ThirdFilter.java and we want to invoke 3rd filter,2nd filter and then 1st filter. Let’s define two more filters and add a @Order annotation with the first filter.

FirstFilter.java

 

SecondFilter.java

ThirdFilter.java

 

Let’s run the SpringMainExample.java, In the console, we can see the third filter has been called first, the second filter has been called second and third filter has been called the third time.

2019-02-21 09:35:11.984 INFO 4044 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘secondFilter’ to: [/*]
2019-02-21 09:35:11.984 INFO 4044 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘firstFilter’ to: [/*]
init() method has been get invoked third filter
init() method has been get invoked second filter
init() method has been get invoked first filter
2019-02-21 09:35:12.307 INFO 4044 — [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]13e16fd: startup date [Thu Feb 21 09:35:09 IST 2019]; root of context hierarchy
2019-02-21 09:35:12.385 INFO 4044 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping

 

Let’s check for doFilter() method. Don’t forget doFilter() will invoked on each request. I am going to hit same rest URI from the postman.

That’s all we have about Filter example in Spring Boot.

you may like –

 

Top