jGuru
Register Email     Password Forgot your
password?
HOME FAQS FORUMS DOWNLOADS ARTICLES PEERSCOPE LEARN

  Search   jGuru Search Help

Question How do I perform browser redirection from a JSP page?
Topics Java:API:JSP
Author Govind Seshadri PREMIUM
Created Nov 5, 1999 Modified Dec 2, 1999


Answer
You can use the response implicit object to redirect the browser to a different resource, as:

response.sendRedirect("http://www.foo.com/path/error.html");

You can also physically alter the Location HTTP header attribute, as shown below:

<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>


Is this item helpful?  yes  no     Previous votes   Yes: 7  No: 0



Comments and alternative answers

Comment on this FAQ entry

You can also use the: <jsp:forward page=&quot...
Kyle Thorson, Apr 21, 2000
You can also use the: <jsp:forward page="/newpage.jsp" />

Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  

See also How do I send a redirect from a servlet? ...
Alex Chaffee PREMIUM, Aug 25, 2000  [replies:1]
See also How do I send a redirect from a servlet?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: See also How do I send a redirect from a servlet? ...
Subramanian Narayanan, Jan 27, 2004
There are two ways of accomplishing this. 1. Get an instance of request dispacher from servletcontext and call the forward method. 2. you can use sendRedirect method of response object.

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Response has already been commited error
Martin Quinn, May 5, 2001  [replies:4]
Can someone post a detailed explanation of why this happens when either trying to send a redirect or use the forward method sometimes?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Response has already been commited error
mike B, Jul 11, 2001
This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed...content-type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc...) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn't finished to set up the header. If not starter to set up the header, there are no problems, but if it 's already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over... i this last case it's like you have a file started with <HTML Tag><Some Headers><Body> some output (like testing your variables...) ... and before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status... It s simply impossible due to the specification of HTTP 1.0 and 1.1 (which are the last ones...) hope this explanation can help though... PS: things are all the same in ASP, PHP, and all languages...The error coming from HTTP spec ;-)

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 1



Reply to this answer/comment  Help  
Re: Response has already been commited error
Nitin Baligar, Oct 16, 2001
The solution for this problem is, On action of page 1 call page 2 and from page 2 redirect to the destination page using response.sendRedirect"destinationUrl.jsp") -Nitin

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 1



Reply to this answer/comment  Help  
Re: Response has already been commited error
Subramanian Narayanan, Jan 27, 2004  [replies:1]
You might have set some headers.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[2]: Response has already been commited error
beryl peng, Mar 20, 2005
what you mean by set header? Thanks

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
response.sendRedirect()
Luc Foisy, Oct 16, 2001  [replies:19]

Is there a method to send a redirect that will not continue on with the rest of the page.

At the top of my jsp's I have an if check, to check for session existance, if not it redirects back to a login page. But every time this occurs I get null errors cause the page is still trying to continue accessing session variables, silly me thinking sendRedirect would actually redirect completely.

I could 'if block' the whole page, but that gets terribly annoying since I would like to have my connection check in a single include at the top of each page...

Is there a quick solution to this?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: response.sendRedirect()
Nitin Baligar, Oct 16, 2001  [replies:15]
It should work. I am also doing the same thing. i have a include page in all JSPs which checks for the session variables and if those are not set then redirect tothe login page using response.sendRedirect(). It works fine. I belive this is the best way. if you need more information then you can directly send me the code to my personnel email id nitin@it.fedex.com

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Re: response.sendRedirect()
Luc Foisy, Oct 17, 2001  [replies:14]

Yes, it does work.

But when watching the err output, there is null pointer exceptions popping up.(my session variables) Therefore, it leads me to believe that it has in fact redirected the page, but it still continues with the rest of the jsp code.

What I want is to not have to worry about that. I don't need my error logs filled up :)



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Re: Re: response.sendRedirect()
Nitin Baligar, Oct 17, 2001  [replies:13]
I got your problem. Try with <jsp:forward page="login.jsp" /> instead of response.sendRedirect() and if you want to pass any paramateres then you can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward> I hope you will not get error filled up in the error log file.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[4]: response.sendRedirect()
Tom Cook, Jan 1, 2002  [replies:11]

<jsp:forward page="login.jsp"/> is only good if you are responding to a GET request - I get a HTTP 503 Not Implemented if I try it from a POST request, which is how I submit data to a database, since then you don't get all that URL junk.

The answer to the question that was asked, however, is simple. Since your JSP is just translated into a java class, you can include _any_ valid java code in it, including 'return;'. So do something like this:

if( some_condition() )
{
	response.sendRedirect( somelocation );
	return;
}

If you don't think of JSPs as being translated into servlets then you are bound to hit this sort of trouble eventually.

Regards,
Tom



Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re[5]: response.sendRedirect()
Luc Foisy, Feb 18, 2002

Wow. I would have never though of that.

I complete belief that JSP was translated into a servlet, but since I didn't see the methods, didn't think about the return.

Nor would I have thought about the line between the browser and the server. sendRedirect is telling the browser to go somewhere, the return at first glance had me thinking, "Well, where the hell is that going to return to!?"

Cool Deal, thanks!

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Re[5]: response.sendRedirect()
Karen Dando, Jun 21, 2002
Tom: I came across this problem and was browsing this site in hopes of finding an answer.

Sometimes answers that are posted are so complex that it's hard to pick out just the part that pertains to the question.

Not only did you answer the question in an EXTREMELY straight-forward and easy to understand way, but you reminded me of the fact that JSPs get translated into servlets, which, being just past the newbie stage, I had forgotten.

Thanks for your help!

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[5]: response.sendRedirect()
Steve McCallum, Jun 23, 2002  [replies:6]
Hi,

More on the JSP:FORWARD command problems....!!

I have the same sort of problem with the JSP Forward
command under certain conditions as shown below:- The example ----------- - Check in procesing.jsp for sess.getAttribute("fred")
- If null then Redirect to login.jsp with jsp:forward The Conditions -------------- - I start the browser up pointing to my login.jsp
- I then do nothing except change the URL to point
to my processing.jsp page and press enter. Of course,
no user or password has yet been entered, so my
jsp:forward sends me back again to login.jsp to
request the details. - The problem is that after the jsp:forward, processing
returns back to processing.jsp and continues on, hits
a request for a variable that has not been set up
yet and displays error messages inside the login page.
(Error 500 null pointer) As well as error messages in
the log (see below). - According to the sun documentation, the lines in the
source JSP file after the <jsp:forward> element are not
processed. However, this is clearly not true, as I am
using Visual Age for Java 4.0 with Websphere application
server 4.0 and can step through each line of jsp and
observe what is being processed and the output html. - Adding a return statement immediately after the
jsp:forward in processing.jsp causes a compiler error
becuase of unreachable statements. - The only way I can prevent the error messages
appearing in the login page is to use an if...else
clause around the whole processing.jsp. This works
but I still receive error messages in the logfiles eg: java.net.SocketException: socket closed (code=0) java.lang.Throwable(java.lang.String) java.lang.Exception(java.lang.String) java.io.IOException(java.lang.String) java.net.SocketException(java.lang.String) int java.net.SocketInputStream.socketRead(byte [], int, int, java.net.SocketImpl, java.io.FileDescriptor) int java.net.SocketInputStream.read(byte [], int, int) int java.net.SocketInputStream.read() java.lang.String java.io.DataInputStream.readLine() void com.ibm.servlet.engine.http_transport.HttpTransportHandler.parseHeaders(java.io.DataInputStream) void com.ibm.servlet.engine.http_transport.HttpTransportHandler.handleConnection(java.net.Socket) void com.ibm.servlet.engine.http_transport.HttpTransportHandler.run() void java.lang.Thread.run()


Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[6]: response.sendRedirect()
Tom Cook, Jun 23, 2002  [replies:5]

If you get a compiler error due to unreachable statements then that must be because you always redirect to another page. So why bother redirecting? Why not just go straight there?

If you really want to redirect always, then you need to have no statements after the return, and that means no HTML in you JSP after the return. Remember that a JSP does not have to be valid html, it just has to compile to a class that produces valid html.

Tom



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[7]: response.sendRedirect()
Steve McCallum, Jun 24, 2002
It's definitely not always re-directing !

Maybe it's a VisualAge / WebSphere thing. The
generated servlet code contains an "out.print"
statement after the return causing the compile error.
See example below...

JSP Code
--------

<%HttpSession sess = request.getSession(true);
  String owner = (String)sess.getAttribute("userName");

  if ( sess.getAttribute("userName") == null ) {%>
	<jsp:forward page="/login.jsp"/>
	<%return;%>
<%} else { %>
=== NORMAL PROCESSING
<%}%>

WebSphere generated servlet code extract
----------------------------------------
HttpSession sess = request.getSession(true);
String owner = (String)sess.getAttribute("userName");
                    
if ( sess.getAttribute("userName") == null ) {
out.print(new String(_jspx_html_data[4]));
out.clear();
_jspx_cleared_due_to_forward = true;
pageContext.forward("/login.jsp");
out.print(new String(_jspx_html_data[5]));
return;
out.print(new String(_jspx_html_data[6]));
} else {



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[7]: response.sendRedirect()
Steve McCallum, Aug 11, 2003  [replies:2]
Just to explain why the return didnt work in my code samples:-

CODE Example 1  (FAILS to Compile)
----------------------------------

<%if ( SecurityBean.updateUserSession() ) { %>
	<jsp:forward page="C:/display.jsp"/>
	<%return%>;
<%} else {
	session.setAttribute("UseridMessage", "XXX");
}%>

CODE Example 2  (Works OK)
--------------------------

<%if ( SecurityBean.updateUserSession() ) { %>
	<jsp:forward page="C:/display.jsp"/>
	<%return;
} else {
	session.setAttribute("UseridMessage", "XXX");
}%>

Reason is that the IBM Visual Age WebSphere Test environment detects the <%return%>; statement and automatically enters an out.print statement assuming other output is coming. That causes the compiler to complain that there is code following the return. Regards, SMc

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[8]: response.sendRedirect()
KARTHIK JAYABALAN, Mar 2, 2004
Steve, Did you resolve this problem? Please let me know how fixed it. thanks in advance. Karthik

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
« previous beginning next »


Ask A Question



 
Related Links

JSP FAQ

JSP Forum

Sun's JSP home page

SUN's JSP-Interest mailing archive

IBM's "Introduction to JSP" online course

JSP Insider

Wish List
Features
About jGuru
Contact Us

 



The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers