Java: Session attribute is only in next operation
I'm posting some strings in my Session with the call
request.getSession().setAttribute(key, value);
And making the redirect with
response.sendRedirect(urlRedirect);
In almost all cases the values is the开发者_JS百科re after the redirect.
But sometimes I can only read this value in the next page view, not in the redirect. There is no common behavior.
Someone has faced the same problem?
Sessions are backed by a HTTP cookie. On first-time session creation, a cookie will be set in the response header. By default, cookies are bound to a specific context only.
So, if you redirect while the cookie hasn't been set yet, the session will get lost. To go around this, you need to encode the redirect URL.
response.sendRedirect(response.encodeRedirectURL(url));
This appends the jsessionid
identifier to the URL which allows the servletcontainer to locate the right session without help of a cookie.
If you don't like the jsessionid
thing, then consider implementing a filter like this which ensures that the client is aware of the session cookie before the request enters your controller wherein you fire the redirect.
Also, if you redirect to a different context, it won't be able to access the same session. To go around this, you need to configure the servletcontainer to share the session among the contexts. In for example Tomcat, check the emptySessionPath
attribute of the <Connector>
element in /conf/server.xml
.
Such a behaviour can be caused by caching.
If the page you are redirecting to is retrieved from the browser cache, you obviously can't see the result of setAttribute()
on it. So make sure it's actually requested by the browser.
Are you sure you need to do redirect through browser (response.sendRedirect()) and not on the server side (RequestDispatcher.forward())? Latter is faster as there are no network round trip.
The problem was solve by changing the way of submit.
The page was submitting the data only changing the value of location.href to the Servlet Action.
We only call the submit function from the page form, and the session attributes works fine!
精彩评论