Session
-
服务器中登录后可以访问整个网站(浏览器打开即存在)
-
与Cookie的区别
- Cookie是把用户的数据给服务器,浏览器保存(可以保存多个)
- Session是把用户的数据写入到用户独占的Session中,服务器端保存(存太多可能导致服务器崩溃)
- Session对象由服务器端创建
-
使用场景
- 保存一个登录用户信息
- 购物车信息
- 整个网站中需要经常使用的东西
-
使用Session
public class Session02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //编码问题 resp.setCharacterEncoding("utf-8"); req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //得到Session HttpSession session = req.getSession(); //在session中存东西 session.setAttribute("person",new Person("李白",22)); //获取session中的id String id = session.getId(); //判断session是否是新的 if(session.isNew()){ resp.getWriter().write("Session building success"); }else{ resp.getWriter().write(id+"Session 已经存在"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
获取Session
//得到Session HttpSession session = req.getSession(); Person person = (Person)session.getAttribute("person"); resp.getWriter().write("姓名:"+person.getName()+"年方:"+person.getAge());
-
注销Session
-
手动注销(用后端代码实现)
HttpSession session = req.getSession(); //移除Session session.removeAttribute("person"); //手动注销session session.invalidate();
-
自动注销(在web.xml中配置)
<!-- 设置session默认失效时间--> <session-config> <!-- 失效时间/1分钟--> <session-timeout>1</session-timeout> </session-config>
-
-
Cookie与Session运行的逻辑(个人理解)
- Cookie是存在于客户端 req.getCookies(); 通过客户端存储在本地浏览器上,服务器调用。给客户端们颁发一个通行证,每人一个,无论谁访问都必须携带自己通行证。这样服务器就能从通行证上确认客户身份了。这就是Cookie的工作原理。
- Session存在于服务器端req.getSession();客户端使用的时候获取Session的ID,储存在服务器端。 Session是服务器端使用的一种记录客户端状态的机制。