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

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

更多请见:http://www.mark-to-win.com/tutorial/51347.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值