这是我大学里的
java webapps课程.
用户可以将添加属性作为一对(名称和值)添加到会话中.所以我使用了一个hashmap.
用户可以在同一会话中多次添加此类对.因此,我想在会话中存储整个hashmap,每次按下提交按钮时,都应该将该对添加到Map中.但是,使用此代码仅显示最后添加的对.我不知道为什么会这样
Map lijst;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.isNew()) {
lijst = new HashMap();
session.setAttribute("lijst", lijst);
} else {
lijst = (HashMap) 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("");
out.println("
");out.println("
Sessie demo");out.println("");
out.println("
");out.println("
Sessie demo
");out.println("Toevoegen");
HttpSession session = request.getSession();
out.println("
Sessie gegevens
");out.println("
Sessie aangemaakt op: " + new Date(session.getCreationTime()) + "
");out.println("
Sessie timeout: " + ((session.getMaxInactiveInterval()) / 60) + "
");HashMap lijstAttr = (HashMap) session.getAttribute("lijst");
Iterator it = lijstAttr.entrySet().iterator();
out.println("
Sessie attributen (naam - waarde)
");while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
out.println(pairs.getKey() + " " + pairs.getValue());
it.remove();
}
out.println("");
out.println("");
} finally {
out.close();
}
}