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

网友投稿 1901 2022-11-12

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

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

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

使用filter设置要排除的URL

@WebFilter(urlPatterns = "/*")

@Order(value = 1)

public class TestFilter implements Filter {

private static final Set ALLOWEQepkPEoZAKD_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, ServletRespQepkPEoZAKonse res, FilterChain chain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;

HttpServletResponse response = (HttpServletResponse) res;

String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");

boolean allowedPathttp://h = 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也会进行过滤

//过滤所有路径

@Component

public class WebFilter implements Filter(){

//override三个方法

。。。

。。。

@Override

public void init (FilterConfig filterConfig) throws ServletException{

System.out.println("初始化filter");

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Configmap配置与Secret加密
下一篇:1313_pyserial的安装以及文档的生成
相关文章

 发表评论

暂时没有评论,来抢沙发吧~