概述
session对象用于存储特定的用户会话所需的信息 。
会话是指一个终端用户与交互系统进行通讯的过程。
提供一种机制:当用户访问某网站一个以上页面的时候,为这个用户存储相关信息。
session对象是实现了与请求相关的HttpSession接口的对象,内置变量名为session。它封装了属于客户会话的所有信息。
表1 HttpSession的重要方法
方法 |
描述 |
| void setAttribute(String name,Object value) | 将对应的键-值对存入session 对象 |
| Object getAttribute(String name) | 从session 对象中根据键返回值 |
Enumeration getAttributeNames() |
从session 对象中得到所有的键。这些键以Enumeration 形式返回 |
void setMaxInactiveInterval(int interval) |
Specifies the time,in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should nevertimeout. |
| int getMaxInactiveInterval() | Returns the maximum time interval, inseconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method.A negative time indicates the session should never timeout. |
| String getId() | Returns a stringcontaining the unique identifier assigned to this session. |
案例:访问计数
<body>
<%int count=0;
if (session.getAttribute("counter")!=null){//页面第一次访问的时候为键值为null
count = (Integer)session.getAttribute("counter");//获取截至到上一次的访问页面次数
count++;//将本次访问次数加入到访问总次数
}
session.setAttribute("counter",count);//将最新的计数值存储到session
%>
该页面的访问次数为:<%=session.getAttribute("counter") %>//页面显示当前访问总次数
</body>
设置session对象的有效期
session对象是和请求相关的HttpSession对象,内置变量名为session。它封装属于用户会话的所有信息。在session对象的有效期内,session对象封装的信息一直可供各个页面访问。
案例
session.setMaxInactiveInterval(5);//设置有效间隔时间为5秒,5秒内用户没有任何操作,session对象将实效。
<br>interval:<%=session.getMaxInactiveInterval() %>
<视频演示>
服务器何时会创建session对象
它是一个JSP内置对象。在第一次JSP页面被访问时由服务器端创建。当用户在客户端关闭浏览器后,重新打开浏览器,服务器会为这个用户创建一个新的session对象,也就是说原来session对象中存储的信息将不能被继续使用。
<br>id:<%=session.getId() %>
<视频演示>
本页面内容全部由作者姚远原创,请使用者写明出处后再行使用。

