java 在java webapp会话中存储HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13664654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store HashMap in java webapp session
提问by Charlie
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
这是我在大学的 java webapps 课程。用户可以将添加属性作为一对(名称和值)添加到会话中。所以我使用哈希图。用户可以在同一会话中多次添加此类对。因此,我想将整个 hashmap 存储在会话中,每次按下提交按钮时,都应该将这对添加到 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();
}
}
采纳答案by Guido Simone
Looks like you are explicitly cleaning out the hashmap every time you print it.
每次打印时,您似乎都在明确清除哈希图。
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
out.println(pairs.getKey() + " " + pairs.getValue());
it.remove(); // <-----------
}
Just remove the line with it.remove()
只需删除该行 it.remove()