This is for my java webapps class in college.
A user can add add attributes to a session as a pair (name and value). So I use a hashmap.
The user has the possibility to add such pairs multiple times in the same session. Therefore I want to store the entire hashmap in the session and each time the submit button is pressed the pair should be added to the Map. However with this code only the last added pair is shown. I have no idea why this happens
Map<String, String> lijst;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.isNew()) {
lijst = new HashMap<String, String>();
session.setAttribute("lijst", lijst);
} else {
lijst = (HashMap<String, String>) session.getAttribute("lijst");
}
String naam = request.getParameter("naam");
String waarde = request.getParameter("waarde");
lijst.put(naam, waarde);
printResultaat(request, response);
}
private void printResultaat(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Sessie demo</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Sessie demo</h1>");
out.println("<a href=\"voegtoe.html\">Toevoegen</a>");
HttpSession session = request.getSession();
out.println("<h3>Sessie gegevens</h3>");
out.println("<p>Sessie aangemaakt op: " + new Date(session.getCreationTime()) + "</p>");
out.println("<p>Sessie timeout: " + ((session.getMaxInactiveInterval()) / 60) + "</p>");
HashMap<String, String> lijstAttr = (HashMap<String, String>) session.getAttribute("lijst");
Iterator it = lijstAttr.entrySet().iterator();
out.println("<h3>Sessie attributen (naam - waarde)</h3>");
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
out.println(pairs.getKey() + " " + pairs.getValue());
it.remove();
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
Looks like you are explicitly cleaning out the hashmap every time you print it.
Just remove the line with
it.remove()