Issue
I want to create a session in a servlet that I can add data to as multiple requests are coming in. I first check if the session is null, if it is, I get the session and store initial attributes in it. This is what I am hoping for on the first request to the servlet. For further requests, the session should exist and I modify data to the attributes in my session. But in my else condition, my attributes do not exist. How can I get the session to persist through multiple request? thank you
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
int quantity = 0;
Item[] item = new Item[9];
int currRow = Integer.parseInt(request.getParameter("rowNum"));
HttpSession session = request.getSession(false);
if (session == null) {
session = request.getSession();
for (int i = 0; i < 9; i++) {
item[i] = new Item();
item[i].setID(request.getParameter("ID" + (i + 1)));
item[i].setPrice(Double.parseDouble(request.getParameter("p" + (i + 1))));
session.setAttribute(Integer.toString((i + 1)), item[i]);
}
quantity = Integer.parseInt(request.getParameter("q" + currRow));
Item currItem = (Item) session.getAttribute(Integer.toString(currRow));
currItem.setQuantity(currItem.getQuantity() + quantity);
session.setAttribute(Integer.toString(currRow), currItem);
} else {
if (null == session.getAttribute("2")) {
out.println("not exist");
} else {
out.println("exist");
}
}
}
}
FIX:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
int quantity = 0;
Item[] item = new Item[9];
int currRow = Integer.parseInt(request.getParameter("rowNum"));
HttpSession session = request.getSession();
Item currItem;
if (session.getAttribute("1") == null) {
for (int i = 0; i < 9; i++) {
item[i] = new Item();
item[i].setID(request.getParameter("ID" + (i + 1)));
item[i].setPrice(Double.parseDouble(request.getParameter("p" + (i + 1))));
session.setAttribute(Integer.toString((i + 1)), item[i]);
}
quantity = Integer.parseInt(request.getParameter("q" + currRow));
currItem = (Item) session.getAttribute(Integer.toString(currRow));
currItem.setQuantity(currItem.getQuantity() + quantity);
} else {
quantity = Integer.parseInt(request.getParameter("q" + currRow));
currItem = (Item) session.getAttribute(Integer.toString(currRow));
currItem.setQuantity(currItem.getQuantity() + quantity);
}
}
Solution
You can just use request.getSession() instead of request.getSession(false); and the subsequent null check.
It will create a new one if none exists or use the existing one when it is found. The java docs for HtpServletRequest
Answered By - superbAfterSemperPhi