Spring Boot add filter Example

In this article, we will see how to configure Filter using Spring Boot. Also, we will see how to configure multiple filters.

1. What are Filters?

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, or both . In fact it is an object used to intercept the HTTP requests and responses of your application.

By using filter, we can perform two operations:

  • Before sending the request to the controller
  • Before sending a response to the client

2. Filter methods

Spring Boot provides few options to register custom filters in the Spring Boot application. We can define our custom filter implementing this interface. Since Filter interface contains three methods (all of them are invoked by container), our custom filter need to override these methods.

Filter interface methods are:

  1. void init(FilterConfig filterConfig) throws ServletException
    This method tells this filter has been placed into service. It is invoked only one time. If it throws ServletException other tasks will not be performed.
  2. void doFilter(ServletRequest servletRequest, ServletResponse ServletResponse, FilterChain filterChain) throws IOException, ServletException
    It is also invoked each time whenever the client sends a request or server sends a response. In this method, we can check our request is proper or not and even we can modify request and response data.
  3. void destroy()
    It indicates to a filter that it is being taken out of service.

3. Spring Boot add filter – Examples

Here we will some examples of Spring filters:

3.1 Example01: Real-time use of filter

Suppose we want to allow some specific request URI, we can restrict by configuring a filter.

Step1: Create a maven project and name it example01.

Update the pom.xml as below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""






Step2: Define below packages and classes.

Spring Boot add filter - Packages and Classes
Packages and Classes

Update the class as

package com.filter.entity;

public class Student {
    int studentId;
    String studentName;
    String major;
    public int getStudentId() {
        return studentId;
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    public String getStudentName() {
        return studentName;
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    public String getMajor() {
        return major;
    public void setMajor(String major) {
        this.major = major;


Now it is time to set the mappings in

package com.filter.controller;

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.Student;

public class StudentController {

    @RequestMapping(value = "/getstudent",method = RequestMethod.GET)
    public Student getStudent() {
        Student student = new Student();
        student.setStudentName("John Smith");
        student.setMajor("Computer Science");

        return student;


We will define our filter in

package com.filter.filterconfig;


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.stereotype.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



Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks. In order for Spring to be able to recognize a filter, we needed to define it as a bean with the @Component

package com.filter.mainexample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

public class SpringMainExample {
    public static void main(final String[] args) {
        final ConfigurableApplicationContext configurableApplicationContext = SpringApplication
                .run(SpringMainExample.class, args);

Now run the

Spring Boot add filter - Run Result
Run Result

As you see init() method has been invoked while tomcat start, but doFilter() method has not been invoked. If we hit the below URI from postman then doFilter() method will be invoked.

” http://localhost:8080/student/getstudent”

The URL has been defined in the controller class.

Spring Boot add filter - Run Result
Postman result

In console we have content of doFilter() method it will always get invoked with each new request.

Spring Boot add filter - Invoking doFilter()
Invoking doFilter()

3.2 Example02:

The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the



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 org.springframework.stereotype.Component;

public class MyFilter implements Filter {
    public void destroy() {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain)
            throws IOException, ServletException {

        System.out.println("Remote Host:"+request.getRemoteHost());
        System.out.println("Remote Address:"+request.getRemoteAddr());
        filterchain.doFilter(request, response);

    public void init(FilterConfig filterconfig) throws ServletException {}

In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “This is Example02!”


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

public class Application {
    public static void main(String[] args) {, args);
    @RequestMapping(value = "/")
    public String hello() {
        return "This is Example02!";

The pom.xml file is the same as we used in example01.

Build the project using this command:

mvn clean install

Now run the You can see the application has started on the Tomcat port 8080.

Spring Boot add filter - Tomcat status
Tomcat status

Now hit the URL http://localhost:8080.

As you see the remote address and remote host are displayed:

Remote Host and Address
Spring Boot add filter - Result of  the URL
Result of the URL

4. Download the Source Code

You can download the full source code of this example here: Spring Boot add filter Example

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Firouzeh hejazi

A self-motivated and hard-working developer with more than 4 years of extensive experience in developing software in java platforms. A multi-skilled and problem-solving engineer who has participated in implementing a range of applications in different roles. Possess a MSc in Knowledge Engineering and Decision Science.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button