session相关
Session
什么是Session:
- 服务器会给每一个用户(浏览器)创建一个Session对象
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在
- 用户登录之后,整个网站它都可以访问-->保存用户的信息,保存购物车的信息
Session和Cookie的区别
- Cookie是把用户的数据写给 用户的浏览器,浏览器保存(可以保存多个)
- Session把用户的数据写到用户独占的Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务创建
使用场景
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中,经常会使用的数据,我们将它保存在Session中
使用Session
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session存东西
session.setAttribute("name",new Person("杨明",1));
//获取Session的ID
String id = session.getId();
//判断Session是不是新创建的
if (session.isNew()){
resp.getWriter().write("session创建成功,Session ID为"+id);
}else{
resp.getWriter().write("session已经在服务器中存在了,id为"+id);
}
//得到Session
HttpSession session = req.getSession();
Person person =(Person) session.getAttribute("name");
System.out.println(person.toString());
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
会话自动过期,web.xml
<!--设置Session默认失效时间-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>

浙公网安备 33010602011771号