Edit Edit

Java Servlet FAQ


How do you redirect a request to a different URL?


There are two ways to redirect a request to a different URL:

1) use HttpServletResponse's sendRedirect() function:

public void sendRedirect(String location) throws IOException

Notes:

2) set the HTTP response header's Refresh field:

res.setHeader("Refresh", delay + "; URL=" + location)

where delay is the number of seconds to wait before the browser requests the new location

Notes:

For example,

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

public class RedirectURL extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
                      throws ServletException, IOException
    {    
       // set the content type
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();

       // instruct the browser to wait 5 seconds before redirecting to a new URL
       res.setHeader("Refresh", "5; URL=http://www.keysolutions.com");
       
       // output a message that notifies the user that the browser is
       // going to be redirected to a new page
       out.println("<HTML>");
       out.println("<BODY>");
       out.println("The page you requested could not be found.<BR>");
       out.println("Your browser will automatically take you<BR>");
       out.println("to our home page in 5 seconds.<BR>");
       out.println("</BODY>");
       out.println("</HTML>");
    }
}



Last updated 01/03/2000 10:40:48 PM