Note that there are some explanatory texts on larger screens.

plurals
  1. POStore HashMap in java webapp session
    primarykey
    data
    text
    <p>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</p> <pre><code> Map&lt;String, String&gt; lijst; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if (session.isNew()) { lijst = new HashMap&lt;String, String&gt;(); session.setAttribute("lijst", lijst); } else { lijst = (HashMap&lt;String, String&gt;) 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("&lt;html&gt;"); out.println("&lt;head&gt;"); out.println("&lt;title&gt;Sessie demo&lt;/title&gt;"); out.println("&lt;/head&gt;"); out.println("&lt;body&gt;"); out.println("&lt;h1&gt;Sessie demo&lt;/h1&gt;"); out.println("&lt;a href=\"voegtoe.html\"&gt;Toevoegen&lt;/a&gt;"); HttpSession session = request.getSession(); out.println("&lt;h3&gt;Sessie gegevens&lt;/h3&gt;"); out.println("&lt;p&gt;Sessie aangemaakt op: " + new Date(session.getCreationTime()) + "&lt;/p&gt;"); out.println("&lt;p&gt;Sessie timeout: " + ((session.getMaxInactiveInterval()) / 60) + "&lt;/p&gt;"); HashMap&lt;String, String&gt; lijstAttr = (HashMap&lt;String, String&gt;) session.getAttribute("lijst"); Iterator it = lijstAttr.entrySet().iterator(); out.println("&lt;h3&gt;Sessie attributen (naam - waarde)&lt;/h3&gt;"); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); out.println(pairs.getKey() + " " + pairs.getValue()); it.remove(); } out.println("&lt;/body&gt;"); out.println("&lt;/html&gt;"); } finally { out.close(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload