-
什么是Session
当用户请求来自应用程序的Web页时,服务器会给每一个用户(浏览器)创建一个Session对象;
用户在应用程序的Web页之间跳转时,存储在Session对象中的变量将不会丢失,而是在整个用户会话中一直存在下去,默认情况下,只要浏览器没有关闭,这个Session就一直存在。 -
Session的常用方法
isNew()//判断是否是新创建的Session,一般在第一次访问的时候出现 getid()//拿到session的ID getCreationTime()//当前session创建的时间 getLastAccessedTime()//最近的一次访问这个session的时间。 setAttribute()//设置Session的值 getAttribute()//获取Session的值 removeAttribute()//移除Session的值 invalidate()//手动注销Session
-
Session的应用
//往session中添加数据 package com.test.session; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException;public class SessionDemon01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解决乱码问题req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//从请求中得到sessionHttpSession session = req.getSession();//往session中添加数据session.setAttribute("name","张三");//得到session的IDString id = session.getId();//判断session是否为新创建的if (session.isNew()){resp.getWriter().write("session创建成功,sessionID为"+id);}else{resp.getWriter().write("session已经在服务器中存在,sessionID为:"+id);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }//跨Servlet获取Session的值 public class SessionDemon02 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解决乱码问题req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");HttpSession session = req.getSession();//通过键取出值String name = (String) session.getAttribute("name");resp.getWriter().write(name);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} } //注销Session,手动注销 public class SessionDemon03 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();session.removeAttribute("name");//手动注销session.invalidate();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} } //自动注销,在web.xml里加入<session-config> <session-config><!--Session一分钟后失效--><session-timeout>1</session-timeout> </session-config>
-
Session和Cookie的区别
- Cookie是把用户的数据写给用户的浏览器,由浏览器保存,可以保存多个
- Cookie不是很安全,别人可以分析存放在本地的cookie并进行cookie欺骗
- Cookie的有效期在cookie生成的时候设置进去
- Session是在服务端保存的一个数据结构,用来跟踪用户的状态,这个数据可以保存在集群、数据库、文件中
- Session是把用户的数据写进用户独占的session中,服务器保存,登陆信息等重要信息存放入session
- 如果主要考虑到安全应当使用session