简介
- Session 就一个接口(HttpSession)。
- Session它是用来维护一个客户端和服务器之间关联的一种技术。
- 每个客户端都有自己的一个 Session 会话。
- Session 会话中,我们经常用来保存用户登录之后的信息。
创建/获取Session对象
request.getSession()
第一次调用是:创建Session会话
之后调用都是:获取前面创建好的Session会话对象。
-
isNew(); 判断到底是不是刚创建出来的(新的)
- true 表示刚创建
- false 表示获取之前创建
-
getId();
得到 Session的会话id值。
每个会话都有一个ID 值。而且这个ID是唯一的。
Session域存取数据
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key", "value");
resp.getWriter().write("向Session域中写入数据...");
}
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object value = req.getSession().getAttribute("key");
resp.getWriter().write("key:" + value);
}
Session存活控制
Session 默认的超时时间长为 30 分钟 。
Tomcat服务器的配置文件web.xml中默认有以下配置,它表示配置了TomCat服务器下所有Session的超时配置默认时长为:30分钟。
<session-config>
<session-timeout>30</session-timeout>
</session-config>
如果说。你希望你的web工程,默认的Session的超时时长为其他时长。你可以在你自己的web.xml 配置文件中做以上相同的配置。就可以修改你的web工程所有seession的默认超时时长。
- 超时的概念
session的超时指的是,客户端两次请求的最大间隔时长。
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session默认存活时间:" + maxInactiveInterval);//1800
}
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取Session
HttpSession session = req.getSession();
//设置3s超时
session.setMaxInactiveInterval(3);
resp.getWriter().write("已经设置当前Session 3秒后超时!");
}
protected void timeout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取Session
HttpSession session = req.getSession();
//设置无效
session.invalidate();
resp.getWriter().write("已经设置当前Session立即超时!");
}