我在向列表中添加新项目时遇到问题,因为它会覆盖旧项目而不是显示在旧元素下。
我该怎么做才能正确地在旧元素下添加一个新元素,并一键删除所有元素,但是每个新添加的元素都应该出现在旧元素之后,而不是替换它
我的代码:
@WebServlet(name = "HttpSessionServlet", urlPatterns = {"/HttpSessionServlet"})
public class HttpSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
ArrayList notes = (ArrayList)session.getAttribute("notes");
if (notes == null) {
notes = new ArrayList ();
session.setAttribute("notes",notes);
session.invalidate();
}
String note = request.getParameter("note");
if (note != null){
notes.add(note);
notes.remove("note");
}
PrintWriter out = response.getWriter();
out.println("<html>"); out.println("<body>");
out.println("<h1>My notes</h1>");
out.println("<ul>");
for (int i = 0; i < notes.size(); i++)
out.println("<li>" + notes.get(i));
out.println("</ul>");
out.println("<form action='HttpSessionServlet'>");
out.println("<input type='text' name='note'/><br/>");
out.println("<input type='submit' value='Add note'/>");
out.println("</form>");
out.println("<form action='HttpSessionServlet'>");
out.println("<input type='submit' value='Delete'/>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}