获取 修改cookie

        //创建cookie
        Cookie cookie = new Cookie("name","1461519513");
        //设置路径
        cookie.setPath("/cookie_war_exploded/get");
        //设置时间
        cookie.setMaxAge(60*60);
        //添加cookie
        resp.addCookie(cookie);
        req.getRequestDispatcher("/get").forward(req,resp);
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        //接收到的是一个集合
        for(Cookie cookie:cookies){
            System.out.println(cookie.getName()+":"+cookie.getValue());
            //遍历cookie集合
        }
    }

修改cookie

 

注意要name和路径都相同才能覆盖

 当向cookie里存中文时,会出现错误,服务器会无法解析

 

对中文进行编码

Cookie cookie1 = new Cookie(URLEncoder.encode("姓名","UTF-8"),URLEncoder.encode("魏子涵","UTF-8"));//对中文进行编码

对中文进行解码

System.out.println(URLDecoder.decode(cookie.getName(),"UTF-8") +":"+URLDecoder.decode(cookie.getValue(),"UTF-8"));

 

posted @ 2022-04-25 15:16  软工小蜗牛  阅读(138)  评论(0编辑  收藏  举报