Cookie注意事项
浏览器里;分割的就是一个cookie,cookie是一个键值对
getCookies()获取到的就是所有的cookie,浏览器里以;分割
Cookie.setValue()里的值不能放入特殊字符如
[ ] ( ) = , " / ? @ : ;
利用cookie实现简单的商品浏览历史记录
package top.freeme.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;
@WebServlet(name = "RecordServlet", value = "/record")
public class RecordServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset-utf8");
//1.获取到浏览的历史
String record = request.getParameter("record");
String value = null;
Cookie cookie = null;
//3. 处理第二次访问时,需要从客户端获取到上一次存放的cookie值
Cookie[] cookies = request.getCookies();
if(cookies.length> 1){
for (Cookie ck : cookies) {
if("record".equals(ck.getName())){
value = ck.getValue();
value = record+"-"+value;
StringBuilder sb = new StringBuilder();
if (value!=null){
String[] split = value.split("-");
for (int i = 0; i < split.length; i++) {
for (int j = i+1; j < split.length ; j++) {
if (split[i].equals(split[j])){
split[j] = "";
}
}
}
for (String s : split) {
if (!s.equals("")){
sb.append(s+"-");
}
}
value=sb.toString();
}
//-- 设置value
ck.setValue(value);
cookie = ck;
}
}
}else {
cookie = new Cookie("record", record);
}
response.addCookie(cookie);
response.getWriter().write(value);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
前端操作cookie
JS操作cookie比较麻烦