默认的情况下一个浏览器独占一个Session对象。在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器
独占的session中,当用户使用浏览器访问其他程序是,其他程序可以从用户的Session中取出该用户的书序,为程序服务
Cookie和Session的主要区别:
*
cookie是把用户的数据写到用户的浏览器
*
session技术把用户的数据写到用户独占的Session中
每个Session创建的时候都有一个ID号(默认是没有设置有效期的,会一直存在),然后以cookie的形式写给浏览器
从IE8在浏览器不关闭,打开新的一个浏览器的情况下,就有JSESSIONID共享
解决关闭浏览器浏,再打开浏览器创建一个新的session无法获得上次Session的问题:
response.setCharacterEncoding("UTF-8"
);
response.setContentType("text/html"
);
PrintWriter out =
response.getWriter();
HttpSession hs=
request.getSession();
String id=
hs.getId();
System.out.println(id);
Cookie cookie=
new Cookie("JSESSIONID"
,id);
cookie.setMaxAge(3600
);
cookie.setPath("/day_07"
);
response.addCookie(cookie);
hs.setAttribute("name","洗衣机"
);
注意上边的cookie的name不能错,同时path也不能错
当浏览器在Internet选项的隐私-
高级中设置了禁止cookie(第一方表示当前的网站的cookie,第三方表示其他网站的cookie)时,无法向浏览器回写id,
此时在其他的页面无法或的改session,解决办法:
重写URL:
request.getSession();
String url1=response.encodeURL("/day_07/Session_01"
);
String url2=response.encodeURL("/day_07/Session_02"
);后边会跟上JSESSIONID
out.println("<a href="+url1+" target='_blank'>购买</a>"
);
out.println("<a href="+url2+" target='_blank'>结账</a>"
);
------
但是这种方法有个debug是无法解决的;就是重新打开一个新的浏览器无法获得该session
session的配置:tomcat默认的是三十分钟
<session-config>
<session-timeout>分钟</session-timeout>
</session-config>
request.getSession()与request.getSession(false)的区别:
第一个是得到session,同时此时没创建session,会创建一个Session对象,而后者仅仅是获得session对象,不会创建
销毁session:
invalidate()方法