Servlet(cookie的生存时间与请求路径)

来源:互联网 发布:百度seo一本通pdf下载 编辑:程序博客网 时间:2024/05/16 10:53

cookie的生存时间问题

  • 默认情况下,浏览器会将cookie保存在内存里面。只要浏览器不关闭,cookie就会一直保存,浏览器一关闭,cookie就会被删除。
  • 设置cookie的生存时间:
public void setMaxAge(int expiry)Sets the maximum age of the cookie in seconds.A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age.A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
  • expiry(中文意思为过期),单位为秒
  • expiry>0,表示cookie的值将在expiry秒后过期;expiry<0(默认值),表示将cookie保存在内存中;expiry=0,删除cookie;

note:expiry的使用方法,通过将cookie的生存周期设为0,即可删除该cookie

Cookie cookie = new Cookie("username", "tom");cookie.setMaxAge(0);response.addCookie(cookie);

cookie的路径问题

  • 浏览器访问服务器时,会比较cookie的路径是否与要访问的路径匹配,只有路径匹配的cookie才会被发送。

什莫意思?

使用一个简单的项目servlet_demo用来测试,在webapps的biz目录下创建一个a.jsp,在页面开头添加代码块,用来向客户端添加cookie:

<%Cookie cookie = new Cookie("name","tom");response.addCookie(cookie);%>

启动服务器,部署项目.....

在浏览器中请求http://localhost:8080/servlet_demo/biz/a.jsp,在google浏览器中查看cookie,


在这里可以看到我们添加的name和值tom,




解释:只有路径匹配的cookie才会被发送

当我们再次访问与上面路径匹配的url时,浏览器会自动将该cookie发送到服务器。

验证:

  • 获得客户端发送过来的cookie:
Cookie[] getCookies()Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.Returns:        an array of all the Cookies included with this request, or null if the request has no cookies

在biz文件夹中创建文件b.jsp,在开头添加如下代码:

<%Cookie[] cookies = request.getCookies();for (Cookie c : cookies){out.println("<h1>" + c.getName() + ":" + c.getValue() + "</h1>");}%>
在浏览器中访问b.jsp页面,http://localhsot:8080/biz/b.jsp,

可以观察到,与我们之前添加进客户端的cookie的内容和值相同

  • 将b.jsp文件复制到webapps文件夹下重命名为c.jsp,再次访问c.jsp,http://servlet_demo/c.jsp,我们得到,

只有JSESSIONID,原因就是我们访问http://servlet_demo/c.jsp时对应的路径为/servlet_demo,只与JSESSIONID的路径匹配,因此只返回了JSESSIONID这一个cookie。

  • 在biz下创建一个文件夹biz2,将b.xml文件复制到biz2下,重命名为d.xml,我们访问d.jsp,http://servlet_demo/biz/biz2/d.jsp,结果可以自己分析总结了。
  • cookie的默认路径

默认等于添加该cookie的web组件的路径,例如我们在访问http://localhost:8080/servlet_demo/biz/a.jsp时,在浏览器中添加了一个cookie,则该cookie的路径就是/servlet_demo/biz

匹配规则:访问的路径的层级如果小于客户端保存的cookie的路径的层级,则不能获取深层级的cookie;如果请求的路径的层级深于客户端保存的cookie的路径的层级,则会获得浅层级和当前层级的所有cookie

  • 设置cookie的默认的层级
public void setPath(java.lang.String uri)Specifies a path for the cookie to which the client should return the cookie.The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog.

cookie的限制

  • cookie可以被用户禁止
  • 只能保存少量的数据(4k左右)
  • 只能保存字符串,对于中文,需要编码
  • 不安全
原创粉丝点击