How do I send a redirect from a servlet?

Alex Chaffee

First, a definition. "redirect" means sending a response from your servlet to the browser that tells the browser to go to (make a brand new request for) another URL or page. This should not be confused with "forward" which operates inside the servlet engine, without informing the browser of the "new" content. For this function, you can use the RequestDispatcher and/or the JSP <jsp:forward> tag.

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", ""); 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.:
        <title>Page Has Moved</title> 
        <meta http-equiv="Refresh" content="1; url="> 

<body bgcolor="White" text="Navy"> 

You should be transferred automatically to the new page. If 
not please <a href="">click this link</a>. 

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().

See also How do I perform browser redirection from a JSP page?

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact