在重定向过滤器时停止进一步处理

时间:2011-12-09 13:06:06

标签: java servlet-filters

我有URLRewirteFilter,它检查请求的域是否以www开头。并重定向到no-www url。当要重定向请求时,如何停止进一步处理(调用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 个答案:

答案 0 :(得分:33)

只需在return

的末尾添加if语句即可
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);
}

另见: