session 生命周期

         以前看到书上session 的生命周期,知道session的生命周期是在第一次访(即打开浏览器输入地址成功访问)的时候被创建。同时HttpSessionListener接口的sessionCreate会被调用。

等到浏览器关闭或者服务器重启的时候session会被销毁。

          但在最近的实验中发现,在浏览器直接访问默认的servlet时,session并没有被创建出来。而当在servlet中执行    HttpSession session = request.getSession();     时显示session被创建出来。

  由此可见浏览器访问时session 并不是一定会被创建的。

  查api可以发现这么一段:

getSession
HttpSession getSession(boolean create)

Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. 
If create is false and the request has no valid HttpSession, this method returns null. 

To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters:create - true to create a new session for this request if necessary; false to return null if there's no current sessionReturns:the HttpSession associated with this request or null if create is false and the request has no valid sessionSee Also:getSession()
  
getSession
HttpSession getSession()

Returns the current session associated with this request, or if the request does not have a session, creates one.
Returns:the HttpSession associated with this requestSee Also:getSession(boolean)

      划横线部分是说如果create为false 并且request 内没有HttpSession 对象  ,此方法会返回null 说明session默认是不存在的,调用getsession()才会被创建。

      而对于jsp中平常以为session在客户端访问时就被创建,然而事实是直到servlet端程序调用HttpServletRequest.getSession(true)这样的语句时才被创建,想到jsp来自于servlet就不难理解,如果jsp没有显式的使用 <% @page session="false"%> 关闭session ,jsp文件在编译成servlet时会自动加上HttpSession session = HttpServletRequest.getSession(true);     这也是jsp中隐含对象session的来历。

 

  session是服务器端的,浏览器是客户端的,浏览器的关闭和session是没有关系的,session失效基本是以下三种情况:

  1. 超时
  2. 手动注销( session.invalidate();  )
  3. 服务器重启

 

原文地址:https://www.cnblogs.com/the-wang/p/7604249.html