天天看点

springboot配置过滤器filter-注解式@WebFilter, @Order, @ServletComponentScan

        好多文档说的情况都不一样, 针对自己遇到的情况做了总结, 有遇到相似的, 大家可以借鉴一下, 如果不适用你的项目, 可以发出来, 大家一起交流!

1. 首先自定义过滤器类需要实现Filter接口; 添加注解@WebFilter; 其中urlPatterns可以配置过滤的请求路径,以及filterName过滤器名称

package com.example.demo.controller.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author zwy
 * @date 2018/9/13
 */
//@Order规定多个Filter的执行顺序,按照从小到大执行()中的值
@Order(1)
//@WebFilter过滤对应的请求路径
@WebFilter(urlPatterns = {"/joker/user/*"},filterName = "loginFilter")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("我可以过滤/joker/user/的请求");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
           

2. springboot启动入口**application.java中增加@ServletComponentScan注解,

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

/**
 * @author zwy
 */
//加了@ServletComponentScan,无论过滤器类加不加@Componment都可以,单使用@Component会默认过滤/*,
@ServletComponentScan
@SpringBootApplication
public class DemoUserApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(DemoUserApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoUserApplication.class);
    }
}
           

启动你就会发现已经成功了:

springboot配置过滤器filter-注解式@WebFilter, @Order, @ServletComponentScan

如果想配置多个过滤器, 怎么控制过滤的先后顺序,这时就需要在自定义过滤器类上面增加注解@Order(1):

里面的值可以设置任意值, 但是执行的顺序按照此值从小到大执行!

注意:

        有的人会遇到添加@Component, 本人亲测, 如果入口不添加@ServletComponentScan注解, 过滤器添加@Component也可以起作用, 不过你配置的urlPatterns将会失效, 默认会过滤/*, 这时不妨入口添加@ServletComponentScan注解, 这时你会发现会过滤你配置的路径, 而且无论你加不加@Component都不影响!

重点:2楼的朋友指出order注解不起作用,确实是,查看好多博客,大多的解决方案都是配置类里配置顺序才可以,这篇博客的博主给出了底层的不生效的原理:https://www.cnblogs.com/okong/p/correct-webfilter.html.还有就是定义类型称的时候按A-Z是也可以排序,希望大家一起研究,有更好的方案,希望大家能给出来参考

继续阅读