Redirect the browser to a URL from within a servlet

Here are two way to do this:

RedirectServlet1.java:

import java.io.*;
 
import javax.servlet.*;
import javax.servlet.http.*;
 
public class RedirectServlet1 extends HttpServlet
{
   public void doGet (HttpServletRequest request,
                      HttpServletResponse response)
      throws ServletException, IOException 
   {
      response.sendRedirect("http://www.esus.com");
   }
}

Another way has been suggested on a Java forum if the above doesn’t work:

   response.sendRedirect(response.encodeRedirectURL("http://www.esus.com"))

Alternatively, you can use the HTTP headers to redirect the client’s browser after executing your sevlet:
RedirectServlet2.java:

import java.io.*;
 
import javax.servlet.*;
import javax.servlet.http.*;
 
public class RedirectServlet2 extends HttpServlet
{ 
    public void doGet (HttpServletRequest request,
                       HttpServletResponse response) 
        throws ServletException, IOException
        {
            response.setHeader("Location", "http://www.esus.com");
            response.setStatus(301);
        }
}