Java.Web - Cookies 随笔

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 创建cookie(name, value)
    Cookie cookie = new Cookie("username","admin");
    // 设置cookie生命周期(如果没有设置,则关闭浏览器cookie消失)
    cookie.setMaxAge(3200);
    // 把cookie信息回写个浏览器
    response.addCookie(cookie);
    // 读取cookie
    // 获取所有cookie
    Cookie cookies[] = new request.getCookies();
    // 筛选
    for(int i = 0; i < cookies.length; i++){
    Cookie cookie = cookies[i];
    }
  • Cookie存放中文,把中文转成base64码

    1
    2
    3
    4
    String username = java.net.URLEncoder.encode("刘云龙","UTF-8");
    Cookie cookie = new Cookie("username",username);
    cookie.setMaxAge(3200);
    response.addCookie(cookie);
  • Cookie读取中文,把base64码转成中文

    1
    String username = java.net.URLDecoder.decode(cookie.getValue(),"UTF-8");

1.如果cookie重名了,会被替换
2.cookie是明文存放,得加密存放

Cookie案例:提示用户上次登录时间

Gavin Liu wechat
欢迎您扫一扫上面的二维码,订阅我的微信公众号!