首页 > 代码库 > HttpSession的深入分析与研究

HttpSession的深入分析与研究

HTTP是无状态协议,这意味着每次client检索网页时,都要单独打开一个server连接,因此server不会记录下先前client请求的不论什么信息。

有三种方法来维持client与server的会话:

1.网络server能够指定一个唯一的session ID作为cookie来代表每一个client,用来识别这个client接下来的请求。

这可能不是一种有效的方式,由于非常多时候浏览器并不一定支持cookie。所以我们不建议使用这样的方法来维持会话。

2.重写URL

举例来说,http://baidu.com;sessionid=12345, session标识符为sessionid=12345,server能够用这个数据来识别client。

相比而言,重写URL是更好的方式来,就算浏览器不支持cookies也能工作,但缺点是您必须为每一个URL动态指定session ID。就算这是个简单的HTML页面。

3.除了以上几种方法外,JSP利用servlet提供的HttpSession接口来识别一个用户。存储这个用户的全部訪问信息。

JSP引擎将隐含的session对象暴露给开发人员。因为提供了session对象,开发人员就能够方便地存储或检索数据。

下表列出了session对象的一些重要方法:
1public Object getAttribute(String name)
返回session对象中与指定名称绑定的对象。假设不存在则返回null
2public Enumeration getAttributeNames()
返回session对象中全部的对象名称
3public long getCreationTime()
返回session对象被创建的时间, 以毫秒为单位,从1970年1月1号凌晨開始算起
4public String getId()
返回session对象的ID
5public long getLastAccessedTime()
返回client最后訪问的时间,以毫秒为单位,从1970年1月1号凌晨開始算起
6public int getMaxInactiveInterval()
返回最大时间间隔。以秒为单位,servlet 容器将会在这段时间内保持会话打开
7public void invalidate()
 将session无效化。解绑不论什么与该session绑定的对象
8public boolean isNew()
返回是否为一个新的client。或者client是否拒绝增加session
9public void removeAttribute(String name)
移除session中指定名称的对象
10public void setAttribute(String name, Object value) 
使用指定的名称和值来产生一个对象并绑定到session中
11public void setMaxInactiveInterval(int interval)
用来指定时间,以秒为单位,servlet容器将会在这段时间内保持会话有效
那在实践开发中是怎样使用的呢?

以下我们就通过一个简单的样例查看session的使用

web.xml

<servlet>
    <servlet-name>Session</servlet-name>
    <servlet-class>com.qzp.servlet.sessionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Session</servlet-name>
    <url-pattern>/session</url-pattern>
  </servlet-mapping>

sessionTest.jsp

<body>
    <form action="session" method="post">
     <input type="submit" value=http://www.mamicode.com/"查看session">>
sessionServlet

public class sessionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		// 获取session创建时间
		// 通过simpleDateFormat转化日期格式
		Date createTime = new Date(session.getCreationTime());
		SimpleDateFormat st1=new SimpleDateFormat ("yyyy年MM月dd日 HH时mm分ss秒 E");
		String time1=st1.format(createTime);
		// 获取最后訪问页面的时间
		Date lastAccessTime = new Date(session.getLastAccessedTime());
		SimpleDateFormat st2=new SimpleDateFormat ("yyyy年MM月dd日 HH时mm分ss秒 E");
		String time2=st2.format(lastAccessTime);
		//訪问用户的唯一标识id 的key-value
		String userIDValue = http://www.mamicode.com/"0011";>sessionResult.jsp,前台通过EL表达式取到session范围内的值

<body>
    <center>
        <p>Session Tracking</p>
    </center>
    <table border="1" align="center">
        <tr bgcolor="#949494">
            <th>Session info</th>
            <th>Value</th>
        </tr>
        <tr>
            <td>id</td>
            <td>${sessionScope.idKey}</td>
        </tr>
        <tr>
            <td>Creation Time</td>
            <td>${sessionScope.time1}</td>
        </tr>
        <tr>
            <td>Time of Last Access</td>
            <td>${sessionScope.time2}</td>
        </tr>
        <tr>
            <td>Number of visits</td>
            <td>
                ${sessionScope.visitCount}
            </td>
        </tr>
    </table>
</body>
运行结果例如以下:每一次刷新。页面的visitCount都会加1

技术分享

HttpSession的深入分析与研究