Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop further processing when redirecting in a filter

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); } 
like image 232
karolkpl Avatar asked Dec 09 '11 13:12

karolkpl


1 Answers

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:

  • java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
like image 92
BalusC Avatar answered Sep 25 '22 17:09

BalusC