How do I send a redirect from a servlet?
Created May 4, 2012
The standard HttpResponse object has a method, response.sendRedirect(String), that does the right thing with HTTP headers to send an HTTP redirect to the browser. Check the JavaDoc for more details. One important note: you must call sendRedirect() before (or better: instead of) writing any data to the response output stream.
You can do the same thing yourself with response.setHeader("Location", "http://foo.com/"); but sendRedirect() is preferred.
If you want more control -- for instance, to display a custom page to the user for a few seconds before going to the new page -- you can use META HTTP-EQUIV, e.g.:
See also How do I perform browser redirection from a JSP page?
The "1" in the "content" section is the number of seconds the browser should wait. "0" here should produce an almost instantaneous jump, but in that case, you might as well use sendRedirect().
<html>
<head>
<title>Page Has Moved</title>
<meta http-equiv="Refresh" content="1; url=http://foo.com/index.html">
</head>
<body bgcolor="White" text="Navy">
You should be transferred automatically to the new page. If
not please <a href="http://foo.com/index.html">click this link</a>.
</body>
</html>