在筛选器中重定向时停止进一步处理

2022-09-01 15:36:50

我有URLRewirteFilter,它检查请求的域是否以www开头。并重定向到无 www 网址。当请求被重定向时,我如何停止进一步的处理(调用JSF应用程序,调用servlet等)?到目前为止,我有这个:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String sn = req.getServerName().toLowerCase();
    if (sn.startsWith("www.")) {
        String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.reset();
        resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        resp.setHeader("Location", url);
    }
    chain.doFilter(request, response);
}

答案 1

只需在末尾添加一个语句returnif

if (sn.startsWith("www.")) {
    String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    resp.setHeader("Location", url);
    return;
}
chain.doFilter(request, response);

或添加else

if (sn.startsWith("www.")) {
    String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    resp.setHeader("Location", url);
} else {
    chain.doFilter(request, response);
}

另请参阅:


答案 2

推荐