java - servlet可以更改另一个域的cookie吗

标签 java javascript tomcat servlets cookies

我需要更改另一个域的 cookie 值,我知道我们不能使用 javascript 来完成。可以使用 servlet 吗?

我正在尝试这样但没有成功?我错了吗? 我在本地主机的一个 tomcat 中部署了两个 Web 应用程序 namly Cookies1 和 Cookies2

cookie1应用的Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();

//      String Html = "<HTML><BODY>HI</body></html>";
//      pw.write(Html);

        Cookie cookie  =  new Cookie("__utmz", "Arvind");
        cookie.setDomain("http://localhost:8080/Cookie2");
        cookie.setPath("/");

        response.addCookie(cookie);

        //response.getWriter().write(Html);
    }

cookie1应用的Servlet

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("CookieSetDm.doGet()");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                System.out.println(cookies[i].getName() + " <> "+ cookies[i].getValue());
            }
        }
    }

最佳答案

出于安全原因,您不能使用托管在另一个域上的 servlet 或 JavaScript 修改一个域的 cookie。参见 RFC 6265, section 4.1.2.3 :

The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server. For example, the user agent will accept a cookie with a Domain attribute of "example.com" or of "foo.example.com" from foo.example.com, but the user agent will not accept a cookie with a Domain attribute of "bar.example.com" or of "baz.foo.example.com".

但是您可以在一个servlet/脚本中设置一个cookie,然后在同一主机上的另一个servlet/脚本中读取/修改该cookie。你can甚至从在同一主机名/域的另一个端口上运行的服务器读取或修改在同一主机名/域的一个端口上运行的服务器上设置的 cookie - 因此您可以让 Tomcat 在同一服务器上的两个不同端口上运行并交换两者之间的 cookie。


请注意,您在第一个示例中错误地调用了 setDomain - cookie 的这个字段采用域名而不是完整的 URL。所以调用应该是这样的:

cookie.setDomain("localhost");

正如其他答案所指出的,一些浏览器会忽略 localhost 的 cookie,因此您可能根本不想设置 cookie 的这个字段 - 这具有设置 cookie 的效果,它只会被返回到设置它的同一主机(大部分时间是你想要的)。

关于java - servlet可以更改另一个域的cookie吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089722/

相关文章:

java - 正则表达式不起作用,需要一个好的正则表达式来满足以下规则 :

java - 为 Spring Data Neo4j 创建动态查询

javascript - jquery调整大小后元素高度不更新

java - tomcat 7.0 和 tomcat 8.0 之间有什么变化

java - 间歇性 "java.sql.SQLException: org.apache.commons.dbcp.DelegatingStatement is closed."

java - Android 无法删除文件

java - 如何正确检查两个移动椭圆(圆形)之间的碰撞并更新位置+速度

javascript - 与 DOMContentLoaded 不同,在 jQuery 的 .ready() 之前执行的非 jQuery .ready() 替代方案

javascript - 如何通过jquery或javascript在Gridview的一列上添加 'More...'按钮

eclipse - eclipse 中的动态 web 应用程序无法在 apache 服务器上运行