![](/img/trans.png)
[英]Retrieve java object from servlet with ajax and print it with JSTL
[英]Java Servlet & jQuery AJAX - unable to retrieve object from session
不確定如何解決此問題,請在此處尋求幫助。
Ajax調用將用戶信息帶到servlet,我將用戶對象保存在HttpSession中,控制權返回到Ajax,從那里我通過控制器servlet將控制權重定向到下一個JSP頁面。 但是,如果我嘗試從HttpSession檢索對象,則為null ..不知道如何解決此問題。
這是我的firstservlet代碼:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
這是我的Javascript / AJAX代碼,將請求重定向到nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
最后,控制權轉到nextservlet-我要在其中處理數據,然后顯示新的JSP頁面。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
是有問題的,因為我正在使用-> window.location.href =結果將請求發送到nextservlet ..並轉到doGet?
我不確定,但我在Ajax中看到了
url: ‘firstservlet’,
type: 'POST'
然后控制權轉到nextservlet的doGet方法。 它應該是post方法的nextservlet,所以請使用doPost方法。
我不確定...但是嘗試一下
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
可以在doGet方法中嘗試讀取會話屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.