1

嗨,到目前为止,我正在尝试使用 httponly cookie 这是我编写的代码

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

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

    cookie.setHttpOnly(true);
    boolean bol = cookie.isHttpOnly();
    out.println("<br>Cookie is Marked as HttpOnly = " + bol);
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {

        out.println("<br/> From Cookies Array Name is: " 
            + cookies[i].getName());
        out.println("<br/> From Cookies Array Value is: "
            + cookies[i].getValue());
        out.println("<br/> From Cookies Array isHttpOnly: "
            + cookies[i].isHttpOnly());
        }
    }
    out.println("<br/> <br/>");

    cookie.setHttpOnly(false);
    boolean bol1 = cookie.isHttpOnly();
    out.println("<br>Cookie is Marked as HttpOnly = " + bol1);
    Cookie[] cookies1 = req.getCookies();
    if (cookies1 != null) {
        for (int i = 0; i < cookies1.length; i++) {
        out.println("<br/> From Cookies Array Name is: "
            + cookies[i].getName());
        out.println("<br/> From Cookies Array Value is: "
            + cookies[i].getValue());
        out.println("<br/> From Cookies Array isHttpOnly: "
            + cookies[i].isHttpOnly());
        }
    }
    out.close();
}

印刷

    Cookie is Marked as HttpOnly = true
From Cookies Array Name is: mycookie
From Cookies Array Value is: hi
From Cookies Array isHttpOnly: false


Cookie is Marked as HttpOnly = false
From Cookies Array Name is: mycookie
From Cookies Array Value is: hi
From Cookies Array isHttpOnly: false 

请注意,我使用的是 JBoss 7,并且在 web.xml 配置中我已添加但我认为缺少某些内容

<session-config>
        <cookie-config>
            <http-only>true</http-only>
        </cookie-config>
    </session-config>
4

1 回答 1

11

浏览器不会回传 cookie 值以外的信息,如 httponly、secure、maxage、path 等。浏览器只发回与 cookie 名称关联的 cookie 值。

您可以通过在 Web 浏览器的开发人员工具集中跟踪 HTTP 流量来亲自查看。在 Chrome/Firebug/IE9 中按 F12 并打开“网络”或“网络”选项卡,然后浏览请求和响应标头。您会看到只有Set-Cookie响应标头在 name=value 旁边包含附加 cookie 参数,并且Cookie请求标头仅包含 name=value。

不用担心,浏览器会记住额外的 cookie 参数。如果您不确定,您始终可以通过创建具有相同名称和路径的新 cookie 来覆盖它。

也可以看看:

于 2012-04-18T21:36:07.770 回答