Tomcat中实现Session小结

2019-10-18 15:39:15丽君

然后,每次从请求中获取打印cookie信息,从响应中获取打印Header的Set-Cookie信息:

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    if(request.getSession().getAttribute("count") == null){
      request.getSession().setAttribute("count", 0);
      response.getWriter().write(0+"");
    }else{
      int a = Integer.parseInt(request.getSession().getAttribute("count").toString());
      request.getSession().setAttribute("count", ++a);
      response.getWriter().write(a+"");
    }

    Cookie[] cookies = request.getCookies();
    StringBuffer sb = new StringBuffer();
    if(cookies!=null){
      for(Cookie cookie : cookies){
        sb.append(cookie.getName()+":"+cookie.getValue()+",");
      }
      sb.deleteCharAt(sb.length()-1);
    }

    System.out.println("[第"+(++index)+"次访问]from client request, cookies:" + sb);
    System.out.println("[第"+(index)+"次访问]from server response, header-Set-Cookie:" + response.getHeader("Set-Cookie"));;
  }

部署到tomcat后,连续访问该servlet,观察控制台输出,如下,客户端第一次访问服务器的时候,在服务端的响应头里添加了JSESSIONID信息,且接下来客户端的每次访问都会带上该JSESSIONID:

其实这里有一个问题,session劫持

只要用户知道JSESSIONID,该用户就可以获取到JSESSIONID对应的session内容,还是以上面这个例子为例,

我先用IE浏览器访问该站点,比如连续访问了5次,此时,session中的count值为:

查看该会话的Session id,为6A541281A79B24BC290ED3270CF15E32

接下来打开chrome控制台,将IE浏览器获取过来的JSESSIONID信息(“6A541281A79B24BC290ED3270CF15E32”)写入到cookie中,如下

接着删除其中的一个,只留下JSESSIONID为“6A541281A79B24BC290ED3270CF15E32”的cookie;

刷新页面,发现我们从session获取的count值已经变成6了,说明此次chrome浏览器的请求劫持了IE浏览器会话中的session,

Tomcat中的session实现

Tomcat中一个会话对应一个session,其实现类是StandardSession,查看源码,可以找到一个attributes成员属性,即存储session的数据结构,为ConcurrentHashMap,支持高并发的HashMap实现;

  /**
   * The collection of user data attributes associated with this Session.
   */
  protected Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();