在spring boot中使用@WebFilter配置filter(包括排除URL)


   
   
  1. @WebFilter(urlPatterns = “/*”)
  2. @Order(value = 1)
  3. public class TestFilter implements Filter {
  4. private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet( new HashSet<>(
  5. Arrays.asList( “/main/excludefilter”, “/login”, “/logout”, “/register”)));
  6. @Override
  7. public void init(FilterConfig filterConfig) throws ServletException {
  8. System.out.println( “init———–filter”);
  9. }
  10. @Override
  11. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  12. HttpServletRequest request = (HttpServletRequest) req;
  13. HttpServletResponse response = (HttpServletResponse) res;
  14. String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll( “[/]+$”, “”);
  15. boolean allowedPath = ALLOWED_PATHS.contains(path);
  16. if (allowedPath) {
  17. System.out.println( “这里是不需要处理的url进入的方法”);
  18. chain.doFilter(req, res);
  19. }
  20. else {
  21. System.out.println( “这里是需要处理的url进入的方法”);
  22. }
  23. }
  24. @Override
  25. public void destroy() {
  26. System.out.println( “destroy———-filter”);
  27. }
  28. }

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

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

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

猜你喜欢

转载自blog.csdn.net/ZW547138858/article/details/82382893