Humphrey Bogart
Humphrey Bogart

Reputation: 7613

JSP Redirect: Session Loss Issues

Having replaced a <jsp:forward page="URL"> with a response.sendRedirect("URL");, I find I know lose the session once the redirect occurs. Is there a way to preserve the session with a redirect, or to reconstitute the session cookie and send it along with the redirect?

I know I could use JavaScript via window.location = "URL";, but that is far from ideal!

Any help?

Upvotes: 3

Views: 8402

Answers (2)

Cerryk
Cerryk

Reputation: 21

When you use the jsp:forward tag, it is forwarding the request object to the URL indicated by the tag. You are actually forwarding the request object.

When you use the sendRedirect() method of the response object, you are just sending an absolute URL back to the client's web browser. In other words, the response becomes a redirect to the given URL, which the client's browser then calls.

If the data is part of the request, it is lost; so if you are trying to redirect before you set the username attribute of the session, this will occur.

If you are really losing the session, this could indicate several things: 1) If the new URL is not on the same domain, the cookie will not be sent. 2) If the new URL is outside of the cookie path, the cookie will not be sent. 3) The browser is not set to allow cookies. For this to be the case, you would have had to encode URLs when you were using jsp:forward, so I would be surprised if this is the case.

In any of these instances, a new session will be established, and a new cookie will be created with the path of the new domain and URL.

Upvotes: 2

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32094

You should not have to resend the cookie, because if you had a session established, the cookie should already be on the client (the browser).

Are you sure you lose the session? How do you detect this? Do you have a new session in the page represented by the url you redirect to?

Does the browser accept cookies? Otherwise you should use url rewriting. This is the most probable cause. You could try use HttpServletResponse.encodeRedirectURL before passing the url to response.sendRedirect.

Upvotes: 2

Related Questions