在springboot中怎样使用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进行过滤拦截时
1、 明明在@WebFilter(urlPatterns={"/app/online"})中过滤的是/app/online 路径,但是运行之后发现,这个WebFilter过滤器对所有的URL都进行了过滤。
2、 运行之后发现过滤器没有初始化,没有被加载
合适的注解配置filter的方法:
在class 上添加注解@WebFilter(urlPatterns={"/app/online"})
然后在启动类(**Application.java )上添加注解@ServletComponentScan
即可。
代码如下:
在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");
}
}
看完上述内容,你们掌握在springboot中怎样使用filter设置要排除的URL的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。