【发布时间】:2018-06-05 15:35:12
【问题描述】:
您好,我是 java servlet 的新手。我试图使用 cookie 实现简单的购物车问题。在我的网页中,我要求用户输入可以添加到购物车的产品名称。
网页: 简单文本输入(产品名称) 和一个按钮(添加到购物车)
点击按钮后,网页会显示购物车值。
我遇到了一个奇怪的问题。它适用于少于 3 个值。当我尝试添加第三个值时,它只显示最近添加的两个值。例如,如果我分别添加产品 a、b 和 c。它只显示 b 和 c。
购物车 Servlet 代码:
String name = request.getParameter("productname");
Cookie cookie = new Cookie("product", name);
cookie.setMaxAge(100 * 60);
response.addCookie(cookie);
Cookie[] cookies = request.getCookies();
List<String> names = new ArrayList<String>();
names.add(name);
if (cookies != null) {
for (Cookie c: cookies) {
if (c.getName().equals("product")) {
names.add(c.getValue());
}
}
}
PrintWriter writer = response.getWriter();
for (String item: names) {
writer.println("<h4>" + item + "</h4>");
}
index.jsp:
<form method="post" action="Cart">
<input type="text" name="productname" value="Product name">
<input type="submit" value="AddToCart">
</form>
我花了很多时间来弄清楚其中有什么问题。但我找不到任何错误来解释这种奇怪的行为。请帮忙。
【问题讨论】: