我需要更改另一个域的 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/