Java Web笔记 - Sessoin的使用

发布于 2011-11-12 | 更新于 2020-09-20

1、Web服务器跟踪客户状态的四种方法:

① 建立含有跟踪数据的隐藏字段 ② 重写包含额外参数的URL ③ 使用持续的Cookie ④ 使用Servlet API中的Session

2、Session的运行机制:

当一个Session开始时,Servlet容器,将创建一个HttpSession对象,在HttpSession对象中可以存放客户的相关信息。

Servlet容器为HttpSession分配一个唯一的Session ID。Servlet容器把Session ID作为Cookie保存在客户的浏览器中。

每次客户端发送HTTP请求时,Servlet容器可以根据HttpServletRequest对象读取Session ID,从而找到相应的HttpSession对象获取用户的相关信息。

因为客户端的关闭,服务器不知道,所以需要设置Session的有效期。

3、Session相关方法:

getId
String getId()

Returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.

Returns:
a string specifying the identifier assigned to this session

invalidate
void invalidate()

Invalidates this session then unbinds any objects bound to it.

Throws:
IllegalStateException - if this method is called on an already invalidated session

这个方法使得Session失效,从而产生新的Session

void setAttribute(String name,
Object value)

Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced.

Object getAttribute(String name)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

boolean isNew()

Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.

Returns:
true if the server has created a session, but the client has not yet joined

Throws:
IllegalStateException - if this method is called on an already invalidated session

setMaxInactiveInterval
void setMaxInactiveInterval(int interval)

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout.

Parameters:
interval - An integer specifying the number of seconds

两个请求之间少于这个间隔时间,则Session不会失效。默认值为30分钟。

也可以在web.xml文件中设置Session有效期的默认时间:

30

4、Session的生命周期:

当用户第一次访问Web应用中支持Session的某个网页时,就会开始一个新的Session。

接下来当用户浏览该Web应用的不同网页时始终访问同一个Session。

默认情况下,JSP都支持Session,可以显示声明:

<%@ page session=“true” %>

4.1、Session结束生命周期:

以下情况下,Session将会结束生命周期,Servlet容器将Session所占用的资源释放掉:

a、Session过期 b、服务器调用了HttpSession的invalidate()方法(注销用户时可以使用)

注意:客户端关闭浏览器时并不会结束Session的生命周期。因为虽然关闭浏览器时Session ID对应的Cookie(该Cookie位于浏览器的进程上,会话Cookie)销毁了,但是服务器端的Session仍然存在。

4.2、Session的过期:

当Session开启后的规定时间内没有和Web服务器交互,这个Session就会失效。可以通过HttpSession的setMaxInactiveInterval()方法设置允许Session保持不活动状态的时间,如果超过这个时间,Session就会失效。

本文作者: arthinking

本文链接: https://www.itzhai.comjava-web-notes-sessoin-use.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。