Springboot2(7)轻松搞定自定义Filter(过滤器)

过滤器,监听器,拦截器区别
源码地址

过滤器Filter,是Servlet的的一个实用技术了。可通过过滤器,对请求进行拦截,比如读取session判断用户是否登录、判断访问的**请求URL是否有访问权限(黑白名单)**等。主要还是可对请求进行预处理。接下来介绍下,在springboot如何实现过滤器功能

sprinboot中有两种实现方式

1. @WebFilte

利用@WebFilter注解配置

//注册器名称为customFilter,拦截的url为所有
@WebFilter(filterName="customFilter",urlPatterns={"/*"},
        initParams = {
                @WebInitParam(name = "excludeUrl", value = "/exclude")
        })
@Slf4j
@Order(5)
public class CustomFilter implements Filter {
    private String exclusions = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        exclusions = filterConfig.getInitParameter("excludeUrl");
        //项目启动时初始化,只始化一次
        log.info("filter 初始化,excludeUrl:"+exclusions);
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        log.info(request.getRequestURI());
        if (request.getRequestURI().equals(exclusions)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        log.info("CustomFilter 请求处理");
        log.info("请求地址:"+request.getRequestURL());
        //对request、response进行一些预处理
        // 比如设置请求编码
        // servletRequest.setCharacterEncoding("UTF-8");
        // servletResponse.setCharacterEncoding("UTF-8");
        //链路 直接传给下一个过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("filter 销毁");
    }
}

忽略过滤URL的实现

可以在CustomFilter类添加@Component,@Configuration注入filter,但这种方法会导致拿不到initParams设置的值。

正确做法在启动类中添加@ServletComponentScan

@WebFilter常用属性

属性 类型 是否必需 说明
asyncSupported boolean 指定Filter是否支持异步模式
dispatcherTypes DispatcherType[] 指定Filter对哪种方式的请求进行过滤。支持的属性:ASYNC、ERROR、FORWARD、INCLUDE、REQUEST;默认过滤所有方式的请求
filterName String Filter名称
initParams WebInitParam[] 配置参数
displayName String Filter显示名
servletNames String[] 指定对哪些Servlet进行过滤
urlPatterns/value String[] 两个属性作用相同,指定拦截的路径

2. FilterRegistrationBean方式

两个步骤:

  1. 实现Filter接口,实现Filte
@Slf4j
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        log.info("初始化MyFilter");
    }

    @Override
    public void doFilter(ServletRequest srequest, ServletResponse sresponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        log.info("MyFilter 请求处理");
        HttpServletRequest request = (HttpServletRequest) srequest;
        filterChain.doFilter(srequest, sresponse);
    }

}

  1. 添加@Configuration 注解,将自定义Filter加入过滤链
@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
}    

当有多个filter时通过registration.setOrder(1)或者@Order(5)设置执行顺序,数值越小越早执行。

你可能感兴趣的:(springboot2,springboot2)