Seraph Cheng Seraph Cheng - 5 months ago 95x
Javascript Question

Session attribute is lost after invoking a client-side redirect

Previously, the servlet uses

without problem. Session attributes can be retrieved in the subsequent pages being redirected to.

Currently, I am changing the way to send requests. Originally, the Javascript uses
, but I have now changed it to
jQuery.ajax("my_page.jsp?foo=bar", {...});
. Then, the servlet includes a URL in the JSON response instead of
, and in the
function, I use
to navigate to the new page. However, the saved session attributes cannot be fetched in subsequent pages.

I have compared the session IDs by inserting
<%= session.getId() %>
in my JSP pages. They are the same. The issue here is
in the page redirected to.

I am not sure if this matters, but I am in fact doing this task with more than 1 JSP pages:

A.jsp --- (redirect) ---> B.jsp --- (redirect) ---> C.jsp

In this case, how can I get the saved session attributes in


Below is the code snippet I use to save session attribute.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);


CustomObject customObject = new CustomObject();
// ...
session.setAttribute("myAttribute_1", customObject);

PrintWriter writer = response.getWriter();
JsonObject json = new JsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();

json.addProperty("url", "next_page.jsp?foo=bar");

Below is the code snippet for redirecting.

function redirectHandler(data, currentUrl) {
if (data && data.hasOwnProperty('url')) {
var redirectUrl = data.url;
jQuery.get(redirectUrl).done(function(response) {
redirectHandler(response, redirectUrl);
} else {

function sendFormData(method, url, form) {
jQuery.ajax(url, {
'method': method,
'data': parseData(jQuery(form).serializeArray()),
'success': function(data) {
redirectHandler(data, window.location.href);


I have reverted back to using
in my servlet.

On the client side,
is removed and the function
is updated as follows.

function sendFormData(form) {
var data = parseData(jQuery(form).serializeArray());
var f = document.createElement('form');

for (var key in data) {
'type': 'hidden',
'name': key,
'value': data[key]

f.setAttribute('method', form.getAttribute('method'));
f.setAttribute('action', form.getAttribute('action'));

Whenever I want to submit a form, a
event handler is attached. It will call
rather than
as I need to customize the data to be sent.

Only by applying these simple changes, everything works again.

Still, I am looking for an explanation on this weird behavior.


On the server side

HTTP requests are stateless and the sessions are laid on top of HTTP by different means like

  • URL rewriting (e.g. server starts new session and returns its ID to the client, then client appends session id to all subsequent requests http://host:port/path;session_id=12345)
  • cookies (e.g upon session creation server responds with a cookie encoding session ID, and on the server side you expect that cookie to correlate each request with existing session).

It is the client's responsibility to ensure that they participate in the session by the means expected by the server. When the server is implemented using Java Servlet API it is either jsessionid cookie or the query parameter with the same name appended to the URL, which identifies the session id.

If the client does not support cookies, using Java Servlet API you will have to redirect to a URL created by HttpServletResponse.encodeRedirectURL(String url).

In order to redirect from a servlet use HttpServletResponse.sendRedirect(String url);.

Responding form the server with standard for HTTP redirects will simplify your design. Jquery does implement these standards and therfore will honour HTTP 301 and 302 responses from the server as ilustrated here so no redirect logic on the client side should be needed.

On the client side

Your client is jquery and its ajax implementation will respect and replay the cookies set for any given domain, when subsequent request will be made to the same domain.

If you are redirecting to a different domain, for jquery to work with CORS sessions, please add xhrFields to your request:

    url: a_cross_domain_url,
    xhrFields: {
      withCredentials: true

as per this answer