@WebFilter exclude url-pattern

霸气de小男生 提交于 2019-11-30 03:29:54

The servlet API doesn't support an "exclude" URL pattern.

Your best bet is to just map on /* and compare the HttpServletRequest#getRequestURI() against the set of allowed paths.

@WebFilter("/*")
public class LoginFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
        Arrays.asList("", "/login", "/logout", "/register")));

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", ""); 

        boolean loggedIn = (session != null && session.getAttribute("Id") != null);
        boolean allowedPath = ALLOWED_PATHS.contains(path);

        if (loggedIn || allowedPath) {
            chain.doFilter(req, res);
        }
        else {
            response.sendRedirect(request.getContextPath() + "/login");
        }
    }

    // ...
}
nacho4d

You can use initParam to have some excluded patterns and implement your logic. This is basically the same as BalusC's answer except by using initParam it can be written in the web.xml if you want/need to.

Below I am ignoring some binary (jpeg jpg png pdf) extensions:

@WebFilter(urlPatterns = { "/*" },
    initParams = { @WebInitParam(name = "excludedExt", value = "jpeg jpg png pdf") }
)
public class GzipFilter implements Filter {

    private static final Set<String> excluded;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedString = filterConfig.getInitParameter("excludedExt");
        if (excludedString != null) {
            excluded = Collections.unmodifiableSet(
                new HashSet<>(Arrays.asList(excludedString.split(" ", 0))));
        } else {
            excluded = Collections.<String>emptySet();
        }
    }

    boolean isExcluded(HttpServletRequest request) {
        String path = request.getRequestURI();
        String extension = path.substring(path.indexOf('.', path.lastIndexOf('/')) + 1).toLowerCase();
        return excluded.contains(extension);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.print("GzipFilter");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (isExcluded(httpRequest)) {
            chain.doFilter(request, response);
            return;
        }

        // Do your stuff here
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!