Filter example in Spring Boot

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.

Some Basic points about Filter.

  • 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 the Controller/endpoint classes.
  • We can also define multiple filters if needed.
  • We can define our custom filter by implementing this interface. Since the 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.

Filter example using Spring Boot.

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>FilterExample</groupId>
  <artifactId>FilterExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>FilterExample</name>  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
 </parent>
  <dependencies>
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>               
   </dependencies>   
</project>

Step 2 – Define below packages and classes.

Filter example in Spring Boot

 

Book.java

package com.filter.entity;

public class Book {
	int bookId;
	String bookName;
	String bookPrice;
	public int getBookId() {
		return bookId;
	}
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getBookPrice() {
		return bookPrice;
	}
	public void setBookPrice(String bookPrice) {
		this.bookPrice = bookPrice;
	}
	
}

BookController.java

package com.filter.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.filter.entity.Book;
@RestController @RequestMapping("/book") public class BookController { @RequestMapping(value = "/getbook",method = RequestMethod.GET) @ResponseBody public Book getBook() { Book book = new Book(); book.setBookId(1); book.setBookName("rich dad poor dad"); book.setBookPrice("10"); return book; } }

FirstFilter.java

package com.filter.filterconfig;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
public class FirstFilter implements Filter{
		
       //this method will be called by container when we send any request 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws      IOException, ServletException {
		
		System.out.println("doFilter() method is invoked");
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		System.out.println("Context path is  "+httpServletRequest.getContextPath());
		chain.doFilter(httpServletRequest, httpServletResponse);
		System.out.println("doFilter() method is ended");		
	}
	
	// this method will be called by container while deployment
	public void init(FilterConfig config) throws ServletException {		
		System.out.println("init() method has been get invoked");
		System.out.println("Filter name is "+config.getFilterName());
		System.out.println("ServletContext name is"+config.getServletContext());
		System.out.println("init() method is ended");
	}	
	public void destroy() {
		//do some stuff like clearing the resources		
	}
}

SpringMainExample.java

package com.filter.mainexample;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import com.filter.filterconfig.FirstFilter;

@SpringBootApplication(scanBasePackages={"com.filter.*"})
//@EntityScan("com.filter.*") 
public class SpringMainExample {
	public static void main(final String[] args) {
		final ConfigurableApplicationContext configurableApplicationContext = SpringApplication
				.run(SpringMainExample.class, args);
	}			
}

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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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 isorg.apache.catalina.core.ApplicationContextFacade@4c8641
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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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

Filter Chaining Example using Spring Boot(Filter ordering Using @Order annotation).

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

package com.filter.filterconfig;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class FirstFilter implements Filter{
        //this method will be called by container when we send any request 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		System.out.println("doFilter() method is invoked first filter");
		chain.doFilter(request, response);		
	}
	
	// this method will be called by container while deployment
	public void init(FilterConfig config) throws ServletException {		
		System.out.println("init() method has been get invoked first filter");
	}
	public void destroy() {
		//do some stuff like clearing the resources		
	}
}

 

SecondFilter.java

package com.filter.filterconfig;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class SecondFilter implements Filter{
		
		// this method will be called by container while deployment
		public void init(FilterConfig config) throws ServletException {				
			System.out.println("init() method has been get invoked second filter");			
		}
	
	        //this method will be called by container when we send any request
		public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {			
			System.out.println("doFilter() method is invoked for second filter");
			chain.doFilter(request, response);
		}		
		public void destroy() {
			//do some stuff like clearing the resources
		}
}

ThirdFilter.java

package com.filter.filterconfig;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class ThirdFilter implements Filter {

	public void init(FilterConfig config) throws ServletException {		
		System.out.println("init() method has been get invoked third filter");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("doFilter() method is invoked for third filter");
		chain.doFilter(request, response);
	}
	public void destroy() {
		// do some stuff		
	}
}

 

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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.

Real-time use of a 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.

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

you may like –