不知道什么问题啊
package CookiesDemo;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Util.CookiesUtils;
public class HistoryServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//接受id
String id = req.getParameter("id");
//获取所有Cookies的信息
Cookie[] cookies = req.getCookies();
//判断是否是第一次
Cookie cookie = CookiesUtils.getCookie(cookies, "history");
if(cookie==null){
//第一次浏览商品
Cookie c = new Cookie("history", id);
c.setPath("/Day11");
c.setMaxAge(60*60*24);
res.addCookie(c);
System.out.println(c);
}else{
//不是第一次浏览商品
//判断是否已经在浏览记录中
String value = cookie.getValue();
String[] split = value.split("-");
//将数组转为集合
LinkedList linkedList = new LinkedList<>(Arrays.asList(split));
//之前浏览过商品
if(linkedList.contains(id)){
//将之前删除放在第一位
linkedList.remove(id);
linkedList.addFirst(id);
}else{
//没有浏览过
//超过3个把最后一个删除添加到第一位
if(linkedList.size()>3){
linkedList.remove();
linkedList.addFirst(id);
}else{
//没到3个
linkedList.addFirst(id);
}
}
//将list元素取出,保存到cookies,写回浏览器
StringBuffer sb = new StringBuffer();
for (String string : linkedList) {
sb.append(string).append("-");
}
String substring = sb.toString().substring(0, sb.length()-1);
System.out.println(substring);
//存入cookie中
Cookie c = new Cookie("history", id);
// c.setPath("/Day11");
c.setMaxAge(60*60*24);
res.addCookie(c);
}
}
}
```java
应该将更新后的浏览记录保存在新的cookie中,但是代码中却将新的浏览记录保存在了一个新的名为c的cookie中,而原先的cookie并没有更新
代码你试试这样改了测试一下
//将list元素取出,保存到cookies,写回浏览器
StringBuffer sb = new StringBuffer();
for (String string : linkedList) {
sb.append(string).append("-");
}
String substring = sb.toString().substring(0, sb.length()-1);
System.out.println(substring);
//将更新后的浏览记录保存在原始cookie中
cookie.setValue(substring);
cookie.setMaxAge(60*60*24);
res.addCookie(cookie);
有用的话请采纳,谢谢喽