SoFunction
Updated on 2025-03-03

Detailed explanation of using springboot filters

One: Filter

1. Introduction to filters

A filter is a filter between the client and the server resource file, helping us filter some requests that do not meet the requirements.

Usually used as Session verification to determine user permissions.

2. Filter life cycle

Using filters is simple, 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 (only only once); this method is automatically called when creating the current filter in the container.
  • destroy method: The program stops calling the destroy() method of Filter (only only once); this method is automatically called when the current filter is destroyed in the container.
  • doFilter method: The doFilter() method will be called if each access request meets the intercepting conditions (the first time the program runs, it will be called after the servlet calls the init() method; no matter how many times it is, it will be called before the doGet() and doPost() methods). This method has 3 parameters, namely ServletRequest, ServletResponse and FilterChain. You can get the HttpServletReguest and HttpServletResponse objects from the parameters for corresponding processing operations.

2: Use annotation to implement filters (@WebFilter)

1. Add this annotation in springboot startup class @ServletComponentScan

@SpringBootApplication
@ServletComponentScan // Filterpublic class Springboot02WebTestApplication {
    (, args);
}

2. Write a filter class to implement the Filter interface

import ;
import ;

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

// urlPatterns filter path filterName filter name@WebFilter(urlPatterns = "/user/*", filterName = "tokenFilter1")
public class TokenFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        (filterConfig);
        ("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ("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");
    }
}

3. Visit, tests I used by Postman software

Add the request header token information to access successfully.

Three: Use non-annotation method to implement filters (directly injected into spring)

Code

import ;

import .*;
import ;
import ;
import ;

public class TokenFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ("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");
    }
}

Configuration File

import .TokenFilter2;
import ;
import ;
import ;


@Configuration
public class FilterConfig {

    // Filter code class    @Bean
    public TokenFilter2 tokenFilter2() {
        return new TokenFilter2();
    }

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

Testing is the same as annotation.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.