Home Products QA Support Contact

How do I redirect urls in Tomcat like mod_rewrite?

You can always use response.redirect("url"), but that exposes the redirection to the client. If you don't want that, use a filter. Here's some sample code for such a filter that redirects based on domain names.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public final class TestFilter implements Filter
private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig)
throws ServletException
this.filterConfig = filterConfig;
public void destroy()
this.filterConfig = null;
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException
if (filterConfig == null)

String sn = request.getServerName();
if (sn.equals("www.domain123.com")
|| sn.equals("domain123.com"))
HttpServletRequest r1 = (HttpServletRequest) request; // in case you need it.
rd = request.getRequestDispatcher("/newdir/index.jsp");
if (rd != null)
rd.forward(request, response);
chain.doFilter(request, response);