调用客户端重定向后,会话属性将丢失 [英] Session attribute is lost after invoking a client-side redirect

查看:160
本文介绍了调用客户端重定向后,会话属性将丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,servlet使用 response.sendRedirect(pages / my_page.jsp?foo = bar); 没有问题。可以在重定向到的后续页面中检索会话属性。

Previously, the servlet uses response.sendRedirect("pages/my_page.jsp?foo=bar"); without problem. Session attributes can be retrieved in the subsequent pages being redirected to.

目前,我正在改变发送请求的方式。最初,Javascript使用 myForm.submit(); ,但我现在已将其更改为 jQuery.ajax(my_page.jsp?foo = bar ,{...}); 。然后,servlet包含JSON响应中的URL而不是 response.sendRedirect(),以及 success 函数,我使用 window.location.replace(url); 导航到新页面。但是,无法在后续页面中获取保存的会话属性。

Currently, I am changing the way to send requests. Originally, the Javascript uses myForm.submit();, 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 response.sendRedirect(), and in the success function, I use window.location.replace(url); to navigate to the new page. However, the saved session attributes cannot be fetched in subsequent pages.

我通过插入<%= session.getId(我已经比较了会话ID)我的JSP页面中有%> 。他们是一样的。这里的问题是 session.getAttribute(myAttribute_1)在重定向到的页面中返回 null

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

我不确定这是否重要,但实际上我正在使用超过1个JSP页面执行此任务:

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

在这种情况下,如何在 C.jsp ?

In this case, how can I get the saved session attributes in C.jsp?

下面是我用来保存会话属性的代码片段。

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);

    response.setContentType("application/json");

    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");
    writer.println(gson.toJson(json));
    writer.close();
}

以下是重定向的代码段。

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 {
        window.location.replace(currentUrl);
    }
}

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






结果



我已经恢复使用我的servlet中的 response.sendRedirect(pages / my_page.jsp?foo = bar)

在客户端, jQuery.ajax()被删除,函数 sendFormData ()更新如下。

On the client side, jQuery.ajax() is removed and the function sendFormData() is updated as follows.

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

    for (var key in data) {
        jQuery('<input>').attr({
            'type': 'hidden',
            'name': key,
            'value': data[key]
        }).appendTo(f);
    }

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

每当我想提交表格时,点击附加了事件处理程序。它将调用 sendFormData(myOriginalForm); 而不是 myOriginalForm.submit(); 因为我需要自定义数据发送。

Whenever I want to submit a form, a click event handler is attached. It will call sendFormData(myOriginalForm); rather than myOriginalForm.submit(); 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.

推荐答案

在服务器端



HTTP请求是无状态的,会话通过不同的方式放在HTTP之上,例如

On the server side

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


  • URL重写(例如,服务器启动新会话并将其ID返回给客户端,然后客户端将会话ID附加到所有后续请求 http:// host:port / path; session_id = 12345

  • cookies (例如,会话创建服务器使用cookie编码会话ID进行响应,并且在服务器端,您希望cookie将每个请求与现有会话相关联)。

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

客户有责任确保他们通过服务器预期的方式参与会话。当使用Java Servlet API实现服务器时,它是 jsessionid cookie或具有相同名称的查询参数附加到URL,用于标识会话ID。

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.

如果客户端不支持cookie,则使用Java Servlet API,您将不得不重定向到由 HttpServletResponse.encodeRedirectURL(String url)创建的
a URL

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

为了从servlet重定向,请使用 HttpServletResponse.sendRedirect(String url);

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

对具有HTTP重定向标准的服务器进行响应将简化您的设计。 Jquery 确实实施了这些标准,因此将来自服务器的 HTTP 301 302 响应 ilustrated here 因此不需要客户端的重定向逻辑。

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.

您的客户端是 jquery ,其ajax实现将尊重并且当后续请求将发送到同一域时,重播为任何给定域设置的cookie。

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.

如果要重定向到其他域,则为 jquery 使用 CORS 会话,请在您的请求中添加 xhrFields

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

$.ajax({
    url: a_cross_domain_url,
    xhrFields: {
      withCredentials: true
    }
});

根据这个答案

这篇关于调用客户端重定向后,会话属性将丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆