Servlet Cookie

·  阅读 37

什么是Cookie

  • Cookie类似键值对,有key和value,都是String类型
  • 后端发给前端的标记物,用来判断段浏览器是否曾经来过。
  • Cookie最大是4kb
  • 最多可以给浏览器20个Cookie

样例

public class cookieTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean flag = true;
        int flag1 = 0;
        String value;
        req.setCharacterEncoding("UTF8");
        resp.setCharacterEncoding("UTF8");
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        for (int i = 0 ;i<cookies.length;i++) {
            if (cookies[i].getName().equals("time")){
                flag = false;
                flag1 = i;
            }
            System.out.println(cookies[i].getName());
        }
        if(flag){
            out.write("第一次访问");
            value = String.valueOf(LocalTime.now());
            Cookie cookie =new Cookie("time", value);
            resp.addCookie(cookie);
        }else{
            out.write("上次访问的时间是"+ cookies[flag1].getValue());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
复制代码

核心如下:

Cookie[] cookies = req.getCookies();
Cookie cookie =new Cookie(name, value);//参数都String
resp.addCookie(cookie);
复制代码

注:无论有没有自己设置cookie,浏览器都会有cookie传入,即Cookie[] cookies = req.getCookies();数组不会为空

删除特定name的cookie,用servlet

样例

public class cookie002 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("time", String.valueOf(LocalTime.now()));//必须要和删除name一样
        cookie.setMaxAge(0);//cookie的最大生命值
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
复制代码

核心

Cookie cookie = new Cookie(name, value);//必须要和删除的name一样
cookie.setMaxAge(0);//cookie的最大生命值,必须为0
resp.addCookie(cookie);
复制代码

另外,如何解决乱码

即编码 URLEncoder.encode(value,"UTF-8")与解码 URLDecoder.decode(value,"UTF-8")

核心

String value = "中文";
Cookie cookie1 = new Cookie("name", URLEncoder.encode(value,"UTF-8"));//编码
String decoder = URLDecoder.decode(cookie1.getValue(),"UTF-8");//解码


复制代码
分类:
后端
标签:
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改