在JSP页面中创建的Cookie在Servlet中不可用,只有JSESSIONID cookie是可用的 [英] Cookies created in JSP page are not available in Servlet, only the JSESSIONID cookie is available

查看:81
本文介绍了在JSP页面中创建的Cookie在Servlet中不可用,只有JSESSIONID cookie是可用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个JSP页面,该页面创建了两个cookie,并将其添加到响应对象.该页面具有一个提交按钮,该按钮调用servlet对象.并且该servlet将尝试访问由先前的JSP页面存储的cookie,但是它只能访问JSESSIONID cookie.这是怎么引起的,我该如何解决?

I have created a JSP page which creates two cookies and adds it to response object. This page having a submit button which calls a servlet object. And this servlet will try to access cookies stored by the prior JSP page, but it is only able to access JSESSIONID cookie. How is this caused and how can I solve it?

推荐答案

当您未明确设置Cookie路径时,就会发生这种情况.然后它将默认为请求URI中的当前文件夹.当Cookie的路径与当前请求URI匹配时,浏览器只会将Cookie发送回去.

This will happen when you haven't explicitly set the cookie path. It will then default to the current folder in the request URI. Browser will only send the cookie back when cookie's path matches the current request URI.

因此,假设您的JSP具有URI /pages/some.jsp ,那么在JSP中创建的任何cookie的默认路径都将为/pages .这意味着浏览器将仅在与/pages/* 匹配的任何请求上将cookie发送回去.如果您的servlet具有URI /someServlet ,则它将不会检索cookie.它只会检索路径为/someServlet /的cookie.

So, imagine that your JSP has the URI /pages/some.jsp, then any cookie created in the JSP will have a default path of /pages. This means that the browser will only send the cookie back on any request matching /pages/*. If your servlet has the URI /someServlet, then it won't retrieve the cookie. It will only retrieve cookies having path /someServlet or /.

如果要在整个应用程序范围内放置Cookie,则需要将路径明确设置为/.

If you want to make your cookie applicationwide, then you need to explicitly set the path to /.

Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);

这也将在运行在不同(子)文件夹中的任何servlet或JSP中提供.

This will then also be available in in any servlet or JSP running on a different (sub)folder.

这篇关于在JSP页面中创建的Cookie在Servlet中不可用,只有JSESSIONID cookie是可用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆