以前,servlet 使用response.sendRedirect("pages/my_page.jsp?foo=bar");
没有问题。可以在重定向到的后续页面中检索会话属性。
目前,我正在更改发送请求的方式。最初,Javascript 使用myForm.submit();
,但我现在已将其更改为jQuery.ajax("my_page.jsp?foo=bar", {...});
。然后,servlet 在 JSON 响应中包含 URL,而不是response.sendRedirect()
,并且在success
功能,我用window.location.replace(url);
导航到新页面。但是,保存的会话属性无法在后续页面中获取。
我通过插入比较了会话 ID<%= session.getId() %>
在我的 JSP 页面中。他们是一样的。这里的问题是session.getAttribute("myAttribute_1")
回报null
在重定向到的页面中。
我不确定这是否重要,但实际上我正在使用超过 1 个 JSP 页面执行此任务:
A.jsp --- (redirect) ---> B.jsp --- (redirect) ---> C.jsp
在这种情况下,如何获取保存的会话属性C.jsp
?
Edit
下面是我用来保存会话属性的代码片段。
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();
}
下面是重定向的代码片段。
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);
}
});
}
Result
我已经恢复使用response.sendRedirect("pages/my_page.jsp?foo=bar")
在我的 servlet 中。
在客户端,jQuery.ajax()
被删除并且函数sendFormData()
更新如下。
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();
}
每当我想提交表格时,click
事件处理程序已附加。它会调用sendFormData(myOriginalForm);
而不是myOriginalForm.submit();
因为我需要自定义要发送的数据。
仅通过应用这些简单的更改,一切都会恢复正常。
尽管如此,我仍在寻找对这种奇怪行为的解释。