【问题标题】:Store HashMap in java webapp session [closed]在java webapp会话中存储HashMap [关闭]
【发布时间】:2012-11-19 19:42:23
【问题描述】:

这是我在大学时的 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();
    }
}

【问题讨论】:

  • 尝试使用调试器单步执行您的代码,看看发生了什么您意想不到的事情。
  • 是的,当然我一开始自己调试并寻找解决方案。 HashMap 的大小始终为 1,因此它不保留以前的条目。现在已经修好了。

标签: java session servlets session-variables


【解决方案1】:

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

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

只需删除带有it.remove()的行

【讨论】:

  • 谢谢!现在可以了。我从其他地方复制了迭代器部分并忘记了 it.remove()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2012-04-30
  • 2015-09-06
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多