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");
  • 相关阅读:
    linux 常用命令(个人记录)
    jmeter 5.0版本更新说明(个人做个记录)
    Netdata---Linux系统性能实时监控平台部署记录
    MySQL Yum存储库 安装、升级、集群
    linux 各项配置汇总
    构建Maven项目自动下载jar包
    计算服务器的pv量算法
    性能计算公式
    jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令
    结构模式
  • 原文地址:https://www.cnblogs.com/huey/p/5448341.html
Copyright © 2011-2022 走看看