您的位置:首页 > 编程语言 > Java开发

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

2017-07-03 19:40 3967 查看
@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 exclude spring boot
相关文章推荐