JavaWeb Session 1. Session概述 2. Session入门

1.1. 什么是Session

Session一般译为会话,是解决Http协议的无状态问题的方案,可以将一次会话中的数据存储在服务器端的内存中,保证在下一次的会话中可以使用。

在客户端浏览器第一次向服务器端发送请求时,服务器端会为这个客户端创建独有的Session,并具有唯一的Session ID,存储在服务器端的内存中。在客户端第二次访问服务器端时,会携带Session ID在请求中,服务器端会根据Session ID查找对应的Session信息,进行进一步地操作。

JavaEE中提供了javax.servlet.http.HttpSession接口,通过该接口可以将共享的数据内容存储在HttpSession对象中,从而解决Http协议的无状态问题。

1.2. 百度百科

Session直接翻译成中文比较困难,一般都译成时域。在计算机专业术语中,Session是指一个终端用户与交互系统进行通信的时间间隔,通常指从注册进入系统到注销退出系统之间所经过的时间。以及如果需要的话,可能还有一定的操作空间。

具体到Web中的Session指的就是用户在浏览某个网站时,从进入网站到关闭这个网站所经过的这段时间,也就是用户浏览这个网站所花费的时间。因此从上述的定义中我们可以看到,Session实际上是一个特定的时间概念。

需要注意的是,一个Session的概念需要包括特定的客户端,特定的服务器端以及不中断的操作时间。A用户和C服务器建立连接时所处的SessionB用户和C服务器建立连接时所处的Session是两个不同的Session

1.3. 维基百科

会话(session)是一种持久网络协议,在用户(或用户代理)端和服务器端之间创建关联,从而起到交换数据包的作用机制,session在网络协议(例如telnetFTP)中是非常重要的部分。

在不包含会话层(例如UDP)或者是无法长时间驻留会话层(例如HTTP)的传输协议中,会话的维持需要依靠在传输数据中的高级别程序。例如,在浏览器和远程主机之间的HTTP传输中,HTTP cookie就会被用来包含一些相关的信息,例如session ID,参数和权限信息等。

1.4. SessionCookie的区别

SessionCookie都是解决Http协议的无状态问题,但是两者之间还是存在一定区别的:

  • Cookie数据存储在客户端的浏览器内存中或本地缓存文件中,Session数据存储在服务器端的内存中。
  • Cookie数据存储安全性较低,Session数据存储安全性较高。
  • Session数据存储在服务器端内存中,访问增多时,降低服务器端性能。而Cookie则不会对服务器端性能造成影响。
  • 单个Cookie存储的数据最大是4KB,一个网站只能存储20CookieSession则没有这个问题。
  • Session在关闭浏览器时失效,而持久Cookie则可以存储更长有效时间。

总的来说,SessionCookie各有优势,不能简单来说谁更优。具体用法要考虑具体案例情况而定。

2. Session入门

2.1. Session常用API

JavaEE提供的javax.servlet.http.HttpSession接口,是Web应用程序开发使用Session的接口,该接口提供了很多API方法,而常用的方法有以下几个:

Method Summary

 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.

 Enumeration

getAttributeNames() 
          Returns an Enumeration of String objects containing the names of all the objects bound to this session.

 void

removeAttribute(String name) 
          Removes the object bound with the specified name from this session.

 void

setAttribute(String name, Object value) 
          Binds an object to this session, using the name specified.

  • 通过Request对象获得HttpSession对象。
HttpSession session = request.getSession();
  • 通过HttpSession对象设置和获取共享数据内容。
session.setAttribute("name", "longestory");
String name = (String)session.getAttribute("name");

2.2. 第一个Session

掌握了如何获取Session对象及向Session对象中设置及获取共享数据内容,下面我们就来利用HttpSession对象实现数据内容共享。

  • 创建一个Servlet用于向HttpSession对象中存储共享数据内容。
public class FirstServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("name", "longestory");
        System.out.println("已经成功向HttpSession对象中存储了共享数据内容name=longestory...");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
  • 创建另一个Servlet用于从HttpSession对象中获取储存的共享数据内容。
public class SecondServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        
        out.println("<h1>你存储的共享数据内容为name="+name+"</h1>");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
  • 配置Web工程的web.xml文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>app.java.session.FirstServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>SecondServlet</servlet-name>
    <servlet-class>app.java.session.SecondServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/first</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>SecondServlet</servlet-name>
    <url-pattern>/second</url-pattern>
  </servlet-mapping>    
</web-app>

2.3. Session其他API

JavaEEjavax.servlet.http.HttpSession接口提供了除常用方法外,还有很多其他方法可供使用:

Method Summary

 long

getCreationTime() 
          Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

 String

getId() 
          Returns a string containing the unique identifier assigned to this session.

 long

getLastAccessedTime() 
          Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

 int

getMaxInactiveInterval() 
          Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.