zoukankan      html  css  js  c++  java
  • Servlet & JSP

    关于 Cookie 的内容,参考 HTTP - Cookie 机制

    获取来自客户端的 cookie

    request.getCookies 方法可以获取来自 HTTP 请求的 cookie,返回的是 javax.servlet.http.Cookie 数组。

    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            resp.getWriter().print("name: " + cookie.getName());
            resp.getWriter().print(", value: " + cookie.getValue());
            resp.getWriter().print(", domain: " + cookie.getDomain());
            resp.getWriter().print(", path: " + cookie.getPath());
            resp.getWriter().print(", maxAge: " + cookie.getMaxAge());
            resp.getWriter().print(", sercure: " + cookie.getSecure());
            resp.getWriter().print(", version: " + cookie.getVersion());
            resp.getWriter().print(", comment: " + cookie.getComment());
            resp.getWriter().println(", httpOnly: " + cookie.isHttpOnly());
        }
    }

    很遗憾,没有诸如 getCookieByName 的方法来通过 cookie 的名称获取 cookie,只能遍历 cookie 数组去匹配想要的 cookie。

    送 cookie 至客户端

    response.addCookie 方法可以将 cookie 送至客户端。

    Cookie cookie = new Cookie("userid", userid);
    resp.addCookie(cookie);

    一旦 cookie 从服务器端发送至客户端,服务器端就不存在可以显示删除 cookie 的方法。但可通过覆盖已过期的 cookie,实现对客户端 cookie 的实质性删除操作。

    Cookie cookie = new Cookie("userid", userid);
    cookie.setMaxAge(0);
    resp.addCookie(cookie);

    中文字符

    如果 cookie 的内容是中文字符,则需要对其编码:

    String username = java.net.URLEncoder.encode("中文字符", "UTF-8");
    Cookie cookie = new Cookie("username", username);
    resp.addCookie(cookie);

    在获取 cookie 时则再对其解码:

    java.net.URLDecoder.decode(cookie.getValue(), "UTF-8");

    httpOnly 字段

    在 servlet3.0 之前,javax.servlet.http.Cookie 没有提供设置 httpOnly 字段的方法。可以通过 Set-Cookie 首部来设置 httpOnly 字段。

    resp.addHeader("Set-Cookie", "testcookie=test; Path=/; HttpOnly");
  • 相关阅读:
    location.href使用方法总结
    Ubuntu 12.04 安装JDK 8和Eclipse
    【一】仿微信飞机大战cocos2d-x3.0rc1
    QTP的基本功能介绍
    Spring+Ibatis集成开发实例
    Java NIO与IO的差别和比較
    嵌入式Linux常见问题
    递归和迭代之间的差
    大约sources.list和apt-get [转载]
    JVM学习笔记(一)------的基本结构
  • 原文地址:https://www.cnblogs.com/huey/p/5448341.html
Copyright © 2011-2022 走看看