Web阶段:第十七章:Session会话

发布时间 2023-09-05 16:27:34作者: 忘川信使

什么是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分钟了。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120717041