Java HttpOnly Flag

时间:2014-06-01 06:27:48

标签: java servlets cookies httponly

我使用的是Servlet 3.0,我希望使用HttpOnly标志来保护我的cookie。我的web.xml是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">


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

</web-app>

我的Servlet是

response.setContentType("application/json");
PrintWriter pw = response.getWriter();

Cookie cookie = new Cookie("url", "google.com");
cookie.setMaxAge(60 * 60); //1 hour
response.addCookie(cookie);

pw.println("Cookies created");

我的context.xml是

<Context cookies="true" crossContext="true" useHttpOnly="true">
    <SessionCookie httpOnly="true"/>    
</Context>

但我可以从Javascript中读取Cookie。有人能帮助我吗?

1 个答案:

答案 0 :(得分:3)

web.xml仅配置会话cookie。

你应该添加

cookie.setHttpOnly(true);

到您的Servlet。

相关问题