当前位置:文档之家› 九大内置对象之session

九大内置对象之session

JSP的内置对象——session
从客户端访问服务器开始,直到与服务器断开连接为止。

该对象用于保存每个与服务器建立连接的客户端的信息
session 的ID 保存于客户端的cookie中,这个sessionid标识唯一的用户
一、对象ID
服务器为每一个建立连接的session 一个用于识别的字符串
此字符串会传给客户端并保存在cookie 中,以后用这个ID来唯一标识用户
c s first访问一个页面JSP引擎产生一个session对象,同时分配一个String 类型的ID,JSP引擎将这个ID 发给客户端,存在在cookie。

访问该服务器的其他页面,不再分配新的session对象,直到客户端关闭浏览器,服务器才取消该session。

重新打开浏览器重新生成新的session对象。

二、session的有效期限
以下四种情况清空session中的数据
用户关闭浏览器正在使用的程序
关闭网页服务器
用户未向服务器提出请求超过预设的时间tomcat默认30分钟
运行程序结束session
三、访问session中的数据
1.建立session变量
2.返回session中的变量
3.返回所有session中的变量名称
4.清除session中的变量
5.结束session
四、举例1
结果:
浏览器关闭,新开,再连接,直接代开最后一个页面,看显示的效果
五、举例2
1.s1method.jsp
<body>
<h1>session 方法首页面</h1>
<%
session.setAttribute("user1", "sessiontest1");
session.setAttribute("user2", "sessiontest2");
%>
<table border=2>
<tr>
<th align="lest">session建立的时间</th>
<td><%=session.getCreationTime() %></td>
</tr>
<tr>
<th align="lest">session的标识符</th>
<td><%=session.getId() %></td>
</tr>
<tr>
<th align="lest">session最后被请求的时间</th>
<td><%=session.getLastAccessedTime() %></td>
</tr>
<tr>
<th align="lest">session预设结束的时间</th>
<td><%=session.getMaxInactiveInterval() %></td>
</tr>
<%
session.setMaxInactiveInterval(session.getMaxInactiveInterval()+120);
%>
<tr>
<th align="lest">session新的有效时间</th>
<td><%=session.getMaxInactiveInterval() %></td>
</tr>
<tr>
<th align="lest">是否为新建的session</th>
<td><%=session.isNew() %></td>
</tr>
<tr>
<th align="lest">session1对象取值</th>
<td><%=session.getAttribute("user1") %></td>
</tr>
<tr>
<th align="lest">session2对象取值</th>
<td><%=session.getAttribute("user2") %></td>
</tr>
</table>
<%
session.removeAttribute("user1");
//session.invalidate();
%>
<p><a href="sessionMethod.jsp">转到结果页面</a>
</body>
2.sessionMethod.jsp
<%@page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>session方法</title>
</head>
<body>
<h1>session方法第二个页面</h1>
<table border=3>
<tr>
<th align="lest">session建立的时间</th>
<td><%=session.getCreationTime() %></td> </tr>
<tr>
<th align="lest">session的标识符</th>
<td><%=session.getId() %></td>
</tr>
<tr>
<th align="lest">session最后被请求的时间</th>
<td><%=session.getLastAccessedTime() %></td> </tr>
<tr>
<th align="lest">session预设结束的时间</th>
<td><%=session.getMaxInactiveInterval() %></td> </tr>
<tr>
<th align="lest">是否为新建的session</th>
<td><%=session.isNew() %></td>
</tr>
<tr>
<th align="lest">session1对象取值</th>
<td><%=session.getAttribute("user1") %></td> </tr>
<tr>
<th align="lest">session2对象取值</th>
<td><%=session.getAttribute("user2") %></td> </tr>
</table>
</body> </html>
结果:
将session.invalidate() 替换session.removeAttribute(“user1”) 再比较结果
结果:
略。

关闭浏览器,再打开第一个页面,比较ID和之前ID 的值
3.sessionCount.jsp
结果:。

相关主题