WEB开发会话技术04
14.Session生命周期
14.1生命周期说明
-
public void setMaxInactiveInterval(int interval)
:设置session的超时时间(以秒为单位),超过指定的时长,session就会被销毁。 -
值为正数的时候,设置session的超时时长。
-
值为负数时,表示永不超时
-
public int getMaxInactiveInterval()
表示获取session的超时时间 -
public void invalidate()
表示让当前的session会话立即无效 -
如果没有调用
setMaxInactiveInterval(int interval)
来指定session的生命时长,Tomcat会以session的默认时长为准,session的默认时长为30分钟,可以在tomcat目录的conf目录下的web.xml中设置。 -
Session的生命周期指的是:客户端两次请求的最大间隔时长,而不是累积时长。即当客户端访问了自己的session,session的生命周期将将从0开始重新计算。(指的是同一个会话两次请求之间的间隔时间)
cookie的生命周期指的是累积时长
-
Tomcat用一个线程来轮询会话状态,如果某个会话的空闲时间超过设定的最大值,则将该会话销毁。
说明:在存放session对象的map中,会记录所有session对象的生命周期和session的上次被访问时间。Tomcat维护的线程每隔一定时间就会去扫描这个map,如果发现有某个session对象的上次被访问时间已超过了其生命周期,就会将其删除。如果浏览器在对应session对象没有过期的情况下去访问该session,那么这个session的上次访问时间就会被更新成最新访问的时间。
14.2案例演示1
案例演示1:session的生命周期
web.xml:
<!--CreateSession2-->
<servlet>
<servlet-name>CreateSession2</servlet-name>
<servlet-class>com.li.session.CreateSession2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CreateSession2</servlet-name>
<url-pattern>/createSession2</url-pattern>
</servlet-mapping>
<!--ReadSession2-->
<servlet>
<servlet-name>ReadSession2</servlet-name>
<servlet-class>com.li.session.ReadSession2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadSession2</servlet-name>
<url-pattern>/readSession2</url-pattern>
</servlet-mapping>
CreateSession2:
package com.li.session;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class CreateSession2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("CreateSession2 被调用");
//1.创建session
HttpSession session = request.getSession();
System.out.println("CreateSession2 sid= " + session.getId());
//2.设置生命周期为60秒
session.setMaxInactiveInterval(60);
//3.放属性
session.setAttribute("u", "jack");
//4.给浏览器发送一个回复
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print("<h1>创建session成功,设置生命周期为60s</h1>");
writer.flush();
writer.close();
}
}
ReadSession2:
package com.li.session;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class ReadSession2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("ReadSession2 被调用");
//1.获取到session
HttpSession sessio