什么是session
- 服务器会给一个用户(浏览器)创建一个session对象
- 一个session独占一个浏览器,只要浏览没有关闭,这个session就存在
- 用户登录之后,整个网站都可以访问 ->保存用户信息,保存购物车信息
cookie和session的区别
- session还能替代context来共享数据
- cookie是把用户的数据写给浏览器,浏览器保存(可以保存多个)
- session是把用户数据写道用户独占的session中,服务器端保存(保存重要的数据,减少服务器资源浪费)
- session由服务器创建
使用场景
- 保存用户信息
- 购物车信息
- 在整个网站中经常会使用的数据
使用session
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
HttpSession session = req.getSession();
session.setAttribute("name",new Person("石瑛智",25));
String id = session.getId();
PrintWriter writer = resp.getWriter();
if (session.isNew()) {
writer.write("session创建成功,sessionID为"+id);
}else {
writer.write("session已经在服务器中存在了,sessionID为"+id);
}
读取session
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
HttpSession session = req.getSession();
try {
Person person = (Person) session.getAttribute("name");
resp.getWriter().write(person.toString());
} catch (IllegalStateException e){
resp.sendRedirect("makesession");
}catch (NullPointerException e){
resp.sendRedirect("makesession");
}
清除session
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
HttpSession session = req.getSession();
session.invalidate();
try {
Person person = (Person) session.getAttribute("name");
resp.getWriter().write(person.toString() + session.getId());
} catch (IllegalStateException e) {
resp.getWriter().write("清除成功,会话已失效");
}
会话自动过期 在web.xml中配置
<session-config>
<session-timeout>1</session-timeout>
</session-config>