Session()

时间:2023-03-09 04:35:43
Session()

如何使用 Session

Java Api 只给我们一种方式来 获取 当前会话相关的 session:

HttpSession session = request.getSession();
//或
HttpSession session = request.getSession(boolean);

设置值:

session.setAttribute("key", 值对象);

获取值:

对象类型 obj = (对象类型)session.getAttribute("key");
//如
String name = (String)session.getAttribute("key");

删除 session 指定属性健:

session.removeAttribute("key");

清除所有的session,使当前 session 完全失效:

session.invalidate();

session超时周期设置

1. Tomcat 安装位置 conf/web.xml :

<session-config>
<session-timeout>30</session-timeout>
</session-config>

30分种

2. Tomcat 安装位置 conf/server.xml :

<Context path="/test" docBase="/test"
  defaultSessionTimeOut="3600" isWARExpanded="true"
  isWARValidated="false" isInvokerEnabled="true"
  isWorkDirPersistent="false"/>

单位为 秒

3. Java 代码设置:

HttpSession session = request.getSession();
session.setMaxInactiveInterval(1200);

20 分种:

其他说明:

1. session 过期情况:

1>. 客户端浏览器关闭:

2>. session 会话过期;

3>. 客户端会话调用了 .invalidate();

2. 浏览器关闭与session是否还在;

当客户端浏览器关闭后,session 在服务端还是会存在一定时间的,只是当浏览器器再次打开时,就会生成一个新的 session ,浏览器通过生成的 sessionid 属性来 匹配服务端的 session; 那上次的session 虽然还在,但是就访问不到了;

3. <% @ page session="false" %> 是什么情况?:

这句话的意思是,当前不能使用 session, 但是 页面 session 还是可以创建的;

4. session 在什么时候 被创建:

在 程序 调用 HttpServletRequest.getSession(true) 时创建;如果 页面没有使用 <%@ page session="false"%> 时,在 jsp 页面编译成 Servlet 时,会自动 加上 HttpSession session = HttpServletRequest.getSession(true);

http://www.cnblogs.com/editor/p/4114873.html