Java 后台操作写入Token到浏览器Cookie里

后台设置 Token到 Cookie

String cookieValue = "Cookie";
Cookie cookie_token = new Cookie("token",cookieValue);
cookie_token.setMaxAge(3600);
cookie_token.setPath("/");
response.addCookie(cookie_token);

如果 Cookie里面存在中文字符的话,就需要给字符进行编码

request.setCharacterEncoding("UTF-8");
String cookieValue = URLEncoder.encode("中文 Cookie 值", "UTF-8");
Cookie cookie_token = new Cookie("token", cookieValue);
cookie_token.setMaxAge(3600);
cookie_token.setPath("/");
response.addCookie(cookie_token);

后台读取 Cookie

Cookie cookies[] = request.getCookies();
System.out.println("Cookie长度:" + cookies.length);  
if (cookies != null) {
          
   
    for (int i = 0; i < cookies.length; i++) {
          
   
        if (cookies[i].getName().equals("token")) {
          
   
            System.out.println("For 内部Cookie"
                    + URLDecoder.decode(cookies[i].getValue(),
                    "UTF-8"));
        }
    }
}

后台删除 Cookie

Cookie cookie_token = new Cookie("token",null);
cookie_token.setMaxAge(0);
cookie_token.setPath("/");
response.addCookie(cookie_token);

Cookie里面几个参数介绍

MaxAge:过期时间 设置Cookie最大生存时间,以秒为单位,负数的话为浏览器进程,关闭浏览器Cookie消失

Path:指定存放路径 设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问 例如:当前生成Cookie请求为127.0.0.1:8080/gateway/system/cre/token,那么该token默认就存放在/gateway/system路径下

建议生成Cookie时指定路径"/",这样下面的子路径能读取到

经验分享 程序员 微信小程序 职场和发展