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:
- do not send a response body before calling sendRedirect().
- any code in the servlet after the sendRedirect() will not be executed. the client will be immediately redirected to the new URL.
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:
- the header must be set before sending your response body
- this method is useful if you want to display a message before redirecting the client to a different URL
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 |