第三十三章:Session会话

版权声明:作者:java_wxid https://blog.csdn.net/java_wxid/article/details/84030190

作者:java_wxid
什么是Session会话?
1.Session是会话,表示客户端和服务器之间联系的一个对象。
2.Session是一个域对象。
3.Session经常用来保存用户的数据。

如何创建Session和获取(id号,是否为新)
调用一个方法request.getSession().
第一次调用是创建Session对象并返回
之后调用都是获取Session对象。

isNew() 返回当前Session是否是刚创建出来的,返回true表示刚创建。返回false表示获取。

每个Session会话都有自己的唯一标识,就是ID。

Session域数据的存取
setAttribute 保存数据
getAttribute 获取数据

protected void setAttribute(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	String username = request.getParameter("username");
	HttpSession session = request.getSession();
	session.setAttribute("key1", username);
	response.getWriter()
	.write("已经把你请求过来的参数【" + username + "】给保存到Session域中");
}

protected void getAttribute(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	Object attribute = request.getSession().getAttribute("key1");
	response.getWriter().write("你刚刚保存的数据是:" + attribute);
}

Session生命周期控制
在Tomcat服务器上,Session的默认存活时间是:30分钟。因为在Tomcat的配置文件web.xml中早以有如下的配置:
以下的配置决定了在此tomcat服务器上所有的web工程,创建出来的所有Session对象。默认超时时间都是30分钟。

  <!-- ==================== Default Session Configuration ================= -->
  <!-- You can set the default session timeout (in minutes) for all newly   -->
  <!-- created sessions by modifying the value below.                       -->

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

我们也可以给自己的web工程,单独配置超时时间。只需要在自己的web工程中在web.xml配置文件里做相同的配置即可。
以下配置,把自己的web工程所有的Session都配置超时时间为20分钟了。

<!-- 表示当前的web工程,所有创建出来的Session默认超时时间为20分钟 -->
	<session-config>
		<session-timeout>20</session-timeout>
	</session-config>

以上配置文件的配置的方式都是对Tomcat服务器,或对web工程创建出来的所有Session集体生效。
如果想对某个单个的Session进行设置,可以使用api进行单独设置

setMaxInactiveInterval( time ); 这里以秒为单位
如果值是正数,表示指定的秒数后Session就会超时(Session超时就会被销毁)
如果值是负数,表示Session永远不超时(极少使用)

Session的超时,是指客户端和服务器之间两次请求的间隔时间。如果中间没有任何的请求,就会把Session超时掉。

invalidate():使当前会话,马上被超时

protected void deleteNow(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();	
	session.invalidate();// 结束当前Session	
	response.getWriter().write("当前会话已经超时了");
}

protected void life3(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	HttpSession httpSession = request.getSession();
	httpSession.setMaxInactiveInterval(3);// 表示这个Session3秒之后就会超时。
	response.getWriter().write("已经设置了当前Session超时时间为3秒" );
}

protected void defaultLife(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();
	// 获取客户端和服务器之间最大的请求间隔时间。
	// 就是超时时间。位置 为秒
	int maxInactiveInterval = session.getMaxInactiveInterval();
	response.getWriter().write("默认的超时时间为:" + maxInactiveInterval);
}

浏览器和Session之间关联的技术内幕
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/java_wxid/article/details/84030190