Session 的两种实现机制

一、基于Cookie实现Sessionhtml

Session对象的原理在于,服务器能够为客户端建立并维护一个所谓的Session对象,用于存放数据。在建立Session对象的同时,服务 器将会为该Session对象产生一个惟一编号,这个编号称之为SessionID,服务器以Cookie的方式将SessionID存放在客户端。当浏 览器再次访问该服务器时,会将SessionID做为Cookie信息带到服务器,服务器能够经过该SessionID检索到之前的Session对象, 并对其进行访问。须要注意的是,此时的Cookie中仅仅保存了一个SessionID,而相对较多的会话数据保存在服务器端对应的Session对象 中,由服务器来统一维护,这样必定程度保证了会话数据安全性,但增长了服务器端的内存开销。
存放在客户端的用于保存SessionID的Cookie会在浏览器关闭时清除。咱们把用户打开一个浏览器访问某个应用开始,到关闭浏览器为止交互过程称 为一个“会话”。在一个“会话”过程当中,可能会向同一个应用发出了屡次请求,这些请求将共享一个Session对象,由于这些请求携带了相同的 SessionID信息。java

下面的Servlet用来演示Session的工做原理:
浏览器

public void doGet(HttpServletRequest request, HttpServletResponse response)   
   throws ServletException, IOException {   
    response.setContentType("text/html");   
    PrintWriter out = response.getWriter();   
    String option = request.getParameter("option");   
    if ("create".equals(option)) {   
        //得到HttpSession对象   
        HttpSession session = request.getSession();   
        //设置Session对象的最长不活动间隔   
        session.setMaxInactiveInterval(30);   
        //获取Session中的数据   
        List list = (List) session.getAttribute("list");   
        if (list == null) {   
            list = new ArrayList();   
            list.add("hey");   
            //向Session中添加数据   
            session.setAttribute("list", list);   
        } else {   
        list.add("hey");   
    }   
     out.println(list);   
   }elseif ("invalidate".equals(option)) {   
       HttpSession session = request.getSession(false);   
       if (session != null) {   
       //使Session对象失效   
       session.invalidate();   
   }   
}

该Servlet的url-pattern为/testSession。
当浏览器请求地址“.../tst/testSession?option=create”时,Servlet调用request的getSession 方法得到Session对象,若是此时服务器端存在与请求信息中SessionID(做为Cookie信息携带)对应的Session对象,则返回这个 Session对象,不然将会建立一个新的Session对象并将其产生的SessionID以Cookie的形式经过响应信息送回。注 意,Session对象的setMaxInactiveInterval方法用于设置最长不活动间隔,单位是秒,若是出如今这个的时间段内Session 对象没有被存取,则该Session对象将会失效。一般为了保证服务器的性能和出于安全性考虑,这个值要妥善的设置(Tomcat针对Session的 MaxInactiveInterval会有默认的设置)。若setMaxInactiveInterval设置为负值,则表示该Session永不过 期。另外,Session对象分别经过setAttribute和getAttribute方法存取数据,数据以“名称-对象”对的形式存放。该请求对应 的请求和响应的HTTP信息为:安全

请求:   
GET /tst/testSession?option=create HTTP/1.1   
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, **   
Accept-Language: zh-cn   
UA-CPU: x86   
Accept-Encoding: gzip, deflate   
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)   
Host: 192.168.5.100:8080   
Connection: Keep-Alive   
Cookie: JSESSIONID=C69B3053C575ECC8C7FCAF7D189A4FD1   
  
响应   
HTTP/1.1 200 OK   
Server: Apache-Coyote/1.1   
Content-Type: text/html;charset=ISO-8859-1   
Content-Length: 12   
Date: Sun, 29 Jun 2008 07:20:41 GMT  
  
[hey, hey]

注意:请求信息中携带的SessionID值与上一次相应的SessionID之一致。另外响应输出的HTML文本中有两个“hey”,这是由于此次请求Servlet往存放在Session中的list对象中又放置了一个String对象。
当浏览器请求“.../tst/testSession?option=invalidate”时,Servlet会调用Session对象的 invalidate方法用于使该Session对象失效。须要注意的是,此时获取Session对象的方法为重载的 getSession(boolean b)其中boolean类型的参数表示当前请求没有和服务器端的某个Session对象关联时是建立新的Session(参数为true时)仍是返回 null(参数为false时)。服务器

二、基于URL重写 从上面的介绍能够看出,Session对象的正常使用要依赖于Cookie。若是考虑到客户端浏览器可能出于安全的考虑禁用了Cookie,应该使用URL重写的方式使Session在客户端禁用Cookie的状况下继续生效。
下面有两个JSP页面:1.jsp中向Session对象中存入了名为“hi”的一个String类型对象。经过超级连接能够连接到2.jsp,在 2.jsp中将获取Session中名为“hi”的对象,并显示在页面上。须要注意的是:在1.jsp中超级连接的地址并非直接写了“2.jsp”而是 经过resopnse的encodeURL方法对这个地址进行了处理。session

1.jsp 
<%  
session.setAttribute("hi","Do you work or are you a student?");  
%>  
<a href="<%=response.encodeURL("2.jsp")%>">2.jsp</a>   

2.jsp 
<%=session.getAttribute("hi")%>

首先将浏览器的Cookie禁用(注意要重启IE),而后请求1.jsp,响应后点击连接到2.jsp,这个交互过程涉及到两次请求和相应,HTTP信息以下:app

请求1.jsp   
GET /tst/session/1.jsp HTTP/1.1   
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, **   
Referer: http://192.168.5.100:8080/tst/session/1.jsp   
Accept-Language: zh-cn   
UA-CPU: x86   
Accept-Encoding: gzip, deflate   
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)   
Host: 192.168.5.100:8080   
Connection: Keep-Alive   
响应:   
HTTP/1.1 200 OK   
Server: Apache-Coyote/1.1   
Content-Type: text/html;charset=ISO-8859-1   
Content-Length: 33   
Date: Sun, 29 Jun 2008 07:31:36 GMT   
Do you work or are you a student?

注意:因为Cookie的禁用,此次请求协议头中虽然没有携带SessionID的信息,但SessionID的信息做为请求地址的一部分传到了服务器端,这就是URL重写的意义所在。
response的encodeURL方法将根据浏览器是否不支持Cookie决定是否将SessionID信息写入连接地址。
jsp

相关文章
相关标签/搜索