4

这是我在大学时的 java webapps 课程。用户可以将添加属性作为一对(名称和值)添加到会话中。所以我使用哈希图。用户可以在同一会话中多次添加此类配对。因此,我想将整个哈希图存储在会话中,并且每次按下提交按钮时,都应该将这对添加到 Map 中。但是,使用此代码仅显示最后添加的对。我不知道为什么会这样

 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();
    }
}
4

1 回答 1

4

看起来您每次打印时都在明确清除哈希图。

    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        out.println(pairs.getKey() + " " + pairs.getValue());
        it.remove();   // <-----------
    }

只需删除行it.remove()

于 2012-12-01T23:12:31.597 回答