Article From:https://www.cnblogs.com/1a2b/p/9024457.html

Filter once, as the name suggests, filter things and so on. So how to do it, the specific code is as follows

First of all, it is necessary to build a filter package, create a filter class to implement the filter interface, and filter it.

package com.gateway.filter;

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

@Component
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
            HttpServletRequest request=(HttpServletRequest) servletRequest;
        
            HttpServletResponse response=(HttpServletResponse) servletResponse;
            
            System.out.println("Filter implementation");
            
            chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

}

Then the filter class is loaded in the startup class

@Bean
     public FilterRegistrationBean filterRegistrationBean(){
        
        FilterRegistrationBean  filterRegistrationBean=new FilterRegistrationBean();
        
        List<String>urlPatterns=new ArrayList<String>();
        
        filterRegistrationBean.setFilter(new UserFilter());
        
        urlPatterns.add("/user/touser");
        
        filterRegistrationBean.setUrlPatterns(urlPatterns);
        return filterRegistrationBean;
    }

From the above, we filter the path is /user/touser, then the filter and the interceptor advanced who, debug test can learn, when the path /user/touser comes, the advanced entry filter is completed after the interceptor, the final execution after the completion of the completion of the coNtroller

Link of this Article: Springboot- add filter

Leave a Reply

Your email address will not be published. Required fields are marked *