HttpSession
概念:
HttpSession 是服务器端的技术,服务器会为每一个用户创建一个独立的Session。 属于回话的之一。
Session的工作原理:
当用户第一次访问servlet时服务器会给该用户创建一个独立的Session,并且生成一个独立的SessionID,这个sessionId在响应浏览器时会被装进cookie中,同时被保存到浏览器中,当用户下一次访问Servlet时,请求会携带cookie中的sessionId去访问 服务器根据这个Sessionid去查看是否有对应的session对象如果有就是用,没有就创建一个。
(https://blog.csdn.net/wltulongdao001/article/details/79749225)
Session时效:
Session对象在服务器端不能长期保存,它是有时间限制的,超过一定时间没有被访问过的Session对象就应该释放掉,以节约内存。所以Session的有效时间并不是从创建对象开始计时,到指定时间后释放——而是从最后一次被访问开始计时,统计其“空闲”的时间。
(https://blog.csdn.net/yuexianchang/article/details/70568275 )
在servlet中创建HttpSession
request.getSession()
request.getSession(true): 返回一个HTTPSession对象。若没有和昂前JSP页面关联的HttpSession对象,则服务器创建一个新的HttpSession对象返回,若有,则直接返回关联。
request.getSession(false): 若没有和当前JSP页面关联的HttpSession对象 则返回null;
String seldate=request.getParameter("seldate");
System.out.println("seldate------->"+seldate);
String type=request.getParameter("type");
SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
Date d1;
try {
d1 = s.parse(seldate);
ArrayList<Homeworkmaster2> hms=hs.getHomeworkmaster2ByDateAndType(d1.getTime(), type);
ArrayList<SelectAll> sa=uh.todaySelect(d1.getTime(), type);
*//创建获取session对象*
HttpSession se1=request.getSession();
*//保存session中数据*
se1.setAttribute("homelist", hms);
se1.setAttribute("namelist", sa);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在jsp中调用session
调用的servlet
<form class="form-inline" action="HomeWorkServlet">
//集合
ArrayList<Homeworkmaster2> hms=(ArrayList<Homeworkmaster2>)session.getAttribute("homelist");
ArrayList<SelectAll> sa=(ArrayList<SelectAll>)session.getAttribute("namelist");
//
String username=(String)session.getAttribute("uname");
<p class="navbar-brand">欢迎 <%=username %></p>
销毁HttpSession
1).直接调用HttpSession的invalidate()方法:使Httpsession失效
2).服务器卸载了当前WEB应用。
3).超出HttpSession的过期时间。
设置HttpSession的过期时间:单位为S
session.setMaxInactiveInterval(5);
out.print(session.getMaxInactiveInterval());
在web.xml文件中设置HttpSession过期时间。
<session-config>
<session-timeout>30</session-timeout>
</session-config>
系统默认30分钟
(https://blog.csdn.net/qq_36068521/article/details/79949132 )