码迷,mamicode.com
首页 > 其他好文 > 详细

Session 的两种实现机制

时间:2017-02-07 23:41:40      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:create   cep   throw   bsp   共享   creat   str   char   cookie   

1、基于Cookie实现Session

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

下面的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信息为:

 
 1 请求:   
 2 GET /tst/testSession?option=create HTTP/1.1   
 3 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, **   
 4 Accept-Language: zh-cn   
 5 UA-CPU: x86   
 6 Accept-Encoding: gzip, deflate   
 7 User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)   
 8 Host: 192.168.5.100:8080   
 9 Connection: Keep-Alive   
10 Cookie: JSESSIONID=C69B3053C575ECC8C7FCAF7D189A4FD1   
11   
12 响应   
13 HTTP/1.1 200 OK   
14 Server: Apache-Coyote/1.1   
15 Content-Type: text/html;charset=ISO-8859-1   
16 Content-Length: 12   
17 Date: Sun, 29 Jun 2008 07:20:41 GMT  
18   
19 [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时)。

2、基于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方法对这个地址进行了处理。

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

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

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

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



Session 的两种实现机制

标签:create   cep   throw   bsp   共享   creat   str   char   cookie   

原文地址:http://www.cnblogs.com/gengyi/p/6376239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!