在springboot中如何使用filter设置要排除的URL

目录使用filter设置要排除的URLfilter指定过滤URL的常见问题经常会出现如下错误下面总结一下使用正确的1、 指定路径2、 过滤所有路径

使用filter设置要排除的URL

@WebFilter(urlPatterns = "/*")@Order(value = 1)public class TestFilter implements Filter {     private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(            Arrays.asList("/main/excludefilter", "/login", "/logout", "/register")));    @Override    public void init(FilterConfig filterConfig) throws ServletException {        System.out.println("init-----------filter");    }     @Override    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) res;        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");        boolean allowedPath = ALLOWED_PATHS.contains(path);         if (allowedPath) {            System.out.println("这里是不需要处理的url进入的方法");            chain.doFilter(req, res);        }        else {            System.out.println("这里是需要处理的url进入的方法");        }    }     @Override    public void destroy() {        System.out.println("destroy----------filter");    }}

@Order中的value越小,优先级越高。

ALLOWED_PATHS

这个是一个集合,存放的是需要排出的URL,用来判断是否是需要排除的URL。

关于为什么SpringBoot中使用了@WebFilter但是过滤器却没有生效:一定要加上@Configuration注解,@Service其实也可以,其他类似。

filter指定过滤URL的常见问题

在使用Filter对一些自己指定的URL进行过滤拦截时

经常会出现如下错误

1、 明明在@WebFilter(urlPatterns={“/app/online”})中过滤的是/app/online 路径,但是运行之后发现,这个WebFilter过滤器对所有的URL都进行了过滤。

2、 运行之后发现过滤器没有初始化,没有被加载

下面总结一下使用正确的

合适的注解配置filter的方法:

1、 指定路径

在class 上添加注解@WebFilter(urlPatterns={“/app/online”})

然后在启动类(**Application.java )上添加注解@ServletComponentScan

即可。

代码如下:

2、 过滤所有路径

在class上添加@Component或@Configuration 即可

如果添加了@Component或@Configuration,又添加了@WebFilter(),那么会初始化两次Filter,并且会过滤所有路径+自己指定的路径 ,便会出现对没有指定的URL也会进行过滤

//过滤所有路径@Componentpublic class WebFilter implements Filter(){//override三个方法。。。。。。@Override public void init (FilterConfig filterConfig) throws ServletException{ System.out.println("初始化filter"); }}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

一旦有了意志,脚步也会轻松起来。

在springboot中如何使用filter设置要排除的URL

相关文章:

你感兴趣的文章:

标签云: