Stop further processing when redirecting in a filter

karolkpl picture karolkpl · Dec 9, 2011 · Viewed 34k times · Source

I have URLRewirteFilter which checks if requested domain starts with www. and redirects to no-www url. How can I stop futher processing (invoking JSF app, call servlets etc.) when request is to be redirected? So far I have this:

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

Answer

BalusC picture BalusC · Dec 9, 2011

Just either add a return statement to the end of the 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);

or add an 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);
}

See also: