SoFunction
Updated on 2025-03-03

Example code for springboot implementing filters

1. Introduction to filters

1.1 Filter concept

Filter, namely filter, is one of the three major components of javaWeb (Servlet program, Listener listener, Filter filter)

Function: You can intercept requests or process responses. It is often used for permission checking, recording log operations, intercepting filtering requests, setting encoding of request characters, etc.

1.2 Filter life cycle

It is very simple to define a filter. You only need to implement the Filter class and then rewrite its 3 methods.

  • init method: The program starts the init() method that calls Filter, and is only called once forever; this method is automatically called when the current filter is created in the container.
  • destroy method: The program stops calling the destroy() method of Filter and is only called once forever; this method is automatically called when the current filter is destroyed in the container.
  • doFilter method: If each access request meets the intercepting conditions, the doFilter() method will be called. The first time the program runs, the doFilter() method will be called after the servlet calls the init() method; no matter how many requests, it will be called before the servlet's doGet() and doPost() methods are called. This method has 3 parameters, namely ServletRequest, ServletResponse and FilterChain. You can obtain the HttpServletReguest and HttpServletResponse objects from these parameters for corresponding processing operations.

2. Two implementation methods of filters in SpringBoot

2.1 Implementation of filters in annotation method

First, you need to add it in the startup class@ServletComponentScanAnnotation, the startup class is as follows

import ;
import ;
import ;
import ;

@SpringBootApplication
@MapperScan("")
@ServletComponentScan // Filterpublic class MytApplication {
    public static void main(String[] args) {
        (, args);
    }
}

Write filters to implement Filter interface

import ;
import org.;
import org.;
import .*;
import ;
import ;
import ;
import ;

/**
  * @Author:sgw
  * @Date:2023/9/15
  * @Description: Implement filters using annotation (@WebFilter)
  */
@WebFilter(urlPatterns = "/user/*", filterName = "filter1")
public class MyFilter implements Filter {
    private static final Logger logger = ();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        (filterConfig);
        ("MyFilterInit1");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        ("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = ("token");
        ("tokenvalue:{}", token);

        if (token != null) {
            //The method is executed and runs directly to the next filter            (servletRequest, servletResponse);
        } else {
            ("UTF-8");
            ("application/json; charset=utf-8");
            PrintWriter out = ();
            JSONObject res = new JSONObject();
            ("msg", "mistake");
            ("success", "false");
            (());
        }
    }

    @Override
    public void destroy() {
//        ();
        ("destroy");
    }
}

The above filters the request header, that is, the request header must contain the value of key as token in order to continue accessing the specific interface, otherwise the request will terminate the access to the interface.

2.2 Implement filters in non-annotation mode (directly injected into spring)

Define filters and implement Filter interface

import ;
import org.;
import org.;
import .*;
import ;
import ;
import ;

/**
  * @Author:sgw
  * @Date:2023/9/15
  * @Description: Filter implementation method 2: Use non-annotation method to implement filters (directly injected into spring)
  */
public class MyFilter2 implements Filter {
    private static final Logger logger = ();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ("MyFilterInit2");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        ("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = ("token");
        (token);
        //The method is executed and runs directly to the next filter        if(token!=null){
            (servletRequest, servletResponse);
        }else{
            ("UTF-8");
            ("application/json; charset=utf-8");
            PrintWriter out = ();
            JSONObject res = new JSONObject();
            ("msg", "mistake");
            ("success", "false");
            (());
        }
    }

    @Override
    public void destroy() {
        ("destroy");
    }
}

Write filter configuration classes

import .MyFilter2;
import ;
import ;
import ;
/**
  * @Author:sgw
  * @Date:2023/9/15
  * @Description: Filter configuration file for mode two
  */
@Configuration
public class MyFilter2Config {
    // Filter code class    @Bean
    public MyFilter2 myFilter2() {
        return new MyFilter2();
    }

    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(MyFilter2 myFilter2) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        (myFilter2);
        (2);
        ("/user/*");
        ("tokenFilter2");
        return filterRegistrationBean;
    }
}

The effect is the same as the method.

This is the end of this article about the example code of springboot implementing filters. For more related springboot filter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!