软件编程
位置:首页>> 软件编程>> java编程>> 在springboot中如何使用filter设置要排除的URL

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

作者:Airbundey  发布时间:2022-11-06 00:06:01 

标签:springboot,filter,URL

使用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

即可。

代码如下:

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

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

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");
}
}

来源:https://blog.csdn.net/amanicspater/article/details/74267444

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com