springboot @webfilter FilterRegistrationBean

https://blog.csdn.net/east123321/article/details/79694974

https://blog.csdn.net/small_mouse0/article/details/77840130

 

1、@webfilter过滤指定url,在启动类加注解@ServletComponentScan

springboot @webfilter FilterRegistrationBean_第1张图片

2、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.annotation.WebFilter;

@WebFilter(urlPatterns="/task")
public class DemoFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("Filter demo task");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}

}

3、@webfilter过滤全部路径,在filter类上加 @Component 或 @Configuration 注解:

springboot @webfilter FilterRegistrationBean_第2张图片

 

4、FilterRegistrationBean 过滤指定url 或 全部路径,直接在FilterRegistrationBean中配置即可:

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
public class ConfigurationFilter {
	
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());//添加过滤器
        registration.addUrlPatterns("/user");//设置过滤路径,/*所有路径
        //registration.addInitParameter("name", "alue");//添加默认参数
        registration.setName("MyFilter");//设置优先级
        registration.setOrder(2);//设置优先级
        return registration;
    }

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

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain
                filterChain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) srequest;
            System.out.println("this is MyFilter,url :" + request.getRequestURI());
            filterChain.doFilter(srequest, sresponse);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }
}

 

你可能感兴趣的:(Spring,SpringBoot,开发学习)