This post has been updated to my personal blog simonting.gize.io


The Filter interface is provided in the Servlet package for implementing custom filters.

Custom interceptors can be referenced in my previous article

In contrast, interceptors are a feature provided by the Spring framework, while filters are provided by servlets. Here are some key differences between interceptors and filters:

  • Filters are provided by the Servlet package and can only be used for Web applications, not Spring container resources. Interceptors are provided by Spring and can be used for Web applications as well as Application and Swing applications, using Spring container resources.
  • Filters can only work around servlets; Interceptors, on the other hand, drill down before and after methods, and before and after exceptions are thrown.
  • Filter based on function callback; Interceptors are based on Java’s reflection mechanism.
  • .

Implement custom filters

  • 1. Implement the Filter interface and customize the Filter
  • 2. Register filters

We can define multiple filters to form a filter chain. The order of execution can set the priority during registration. The smaller the priority number is, the higher the priority is

Custom filter

Define filter 1

/ * * *@Author zhangting
 * @DescCustom filter 1 *@Date2020/08/04 * * /
@Slf4j
public class MyFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // When the Web application starts, the Web server creates an instance object of Filter and calls the init method to initialize the object, which is executed only once.
        log.info("----- init filter1 -----");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // The actual filtering operation
        log.info("----- doFilter1 -----");
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        // Test
        httpRequest.setAttribute("name"."zhangting");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy(a) {
        // The Filter object bed will reside in memory after it is created and will be destroyed when the Web application is removed or the server stops. This method is executed only once.
        log.info("----- destroy filter1 -----"); }}Copy the code

Define filter 2

/ * * *@Author zhangting
 * @DescCustom filter 2 *@Date2020/08/04 * * /
@Slf4j
public class MyFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // When the Web application starts, the Web server creates an instance object of Filter and calls the init method to initialize the object, which is executed only once.
        log.info("----- init filter2 -----");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // The actual filtering operation
        log.info("----- doFilter2 -----");
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        // Test
        httpRequest.setAttribute("city"."nanjing");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy(a) {
        // The Filter object bed will reside in memory after it is created and will be destroyed when the Web application is removed or the server stops. This method is executed only once.
        log.info("----- destroy filter2 -----"); }}Copy the code

Registration filter

Write a Javaconfig class to register filters

/ * * *@Author zhangting
 * @DescRegister filters@Date2020/08/04 * * /
@Slf4j
@Configuration
public class FilterConfig {

    @Bean
    @Primary
    public FilterRegistrationBean<MyFilter1> registerMyFilter1(a) {
        log.info("register MyFilter1...");
        FilterRegistrationBean<MyFilter1> filterRegistrationBean = new FilterRegistrationBean<MyFilter1>();
        / / register
        filterRegistrationBean.setFilter(new MyFilter1());
        // Sets the urls to be filtered. If this parameter is not set, all urls are filtered by default
        filterRegistrationBean.addUrlPatterns("/v1/filter");
        filterRegistrationBean.setName("myFilter1");
        // Set the priority. The smaller the number, the higher the priority
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean<MyFilter2> registerMyFilter2(a) {
        log.info("register MyFilter2...");
        FilterRegistrationBean<MyFilter2> filterRegistrationBean = new FilterRegistrationBean<MyFilter2>();
        / / register
        filterRegistrationBean.setFilter(new MyFilter2());
        // Sets the urls to be filtered. If this parameter is not set, all urls are filtered by default
        filterRegistrationBean.addUrlPatterns("/v1/filter");
        filterRegistrationBean.setName("myFilter2");
        // Set the priority. The smaller the number, the higher the priority
        filterRegistrationBean.setOrder(2);
        returnfilterRegistrationBean; }}Copy the code

test

Writing test classes

@Slf4j
@RestController
@RequestMapping("/v1")
public class TestController {

    @GetMapping("/filter")
    publicResponseEntity<? > filter(HttpServletRequest request) { Map<String, String> map =new HashMap<>();
        // Add a name to the request in filter 1 and a city to the request in filter 2
        map.put("name", request.getAttribute("name").toString());
        map.put("city", request.getAttribute("city").toString());
        return newResponseEntity<>(map, HttpStatus.OK); }}Copy the code

When the service is started, both filters are registered and initialized by calling the init method.Use postman to send a request to the /v1/filter interface Looking at the logs, you can see that the filters are executed in the order we set, with filter 1 being executed first and then filter 2. The test values we added in filters 1 and 2 are returned to the foreground successfully