首页 > 其他分享 >Cookie存活时间以及Cookie存储中文

Cookie存活时间以及Cookie存储中文

时间:2022-12-10 15:44:40浏览次数:49  
标签:存储 javax 存活 Cookie import cookie c1 response

Cookie存活时间以及Cookie存储中文

 cookie在浏览器中保存多长时间:

1.默认情况下,当浏览器关闭后,Cookie数据被销毁

2.持久化存储:

   setMaxAge(int  seconds)

     正数:将Cookie数据写到硬盘的文件中,持久化存储,cookie存活时间

     负数:默认值

     零:删除cookie消息   

package com.example.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CookieDemo4", value = "/CookieDemo4")
public class CookieDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie c1 = new Cookie("msg", "setMaxAge");
        //2.设置cookie的存活时间
        //c1.setMaxAge(30);//将cookie持久化到硬盘 30秒后自己删除cookie文件
        //c1.setMaxAge(-1);//关闭浏览器cookie数据被销毁
        c1.setMaxAge(0);//删除cookie消息

        //3.发送Cookie
        response.addCookie(c1);

    }
}

 

 

Cookie存储中文:

在tomcat 8 之前 cookie不能直接存储中文数据

  需要将中文数据转码,一般采用URL编码。(%E3)

在tomcat  8 之后 cookie支持中文数据

@WebServlet(name = "CookieDemo4", value = "/CookieDemo4")
public class CookieDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie c1 = new Cookie("msg", "张三");
      //2.发送Cookie
        response.addCookie(c1);

    }
}

 

标签:存储,javax,存活,Cookie,import,cookie,c1,response
From: https://www.cnblogs.com/qihaokuan/p/16971685.html

相关文章