servlet中的session不一定会被创建。

     以前在树上看session的生命周期,都知道session的生命周期是在客户第一次访问(即打开浏览器输入地址,成功访问)的时候创建。

     同时HttpSessionListener接口(实现的监听器)的sessionCreated方法会被调用。

     等到用户关闭浏览器,或者服务器重启的时候session被关闭,并且HttpSessionListener接口的sessionDestroyed方法会被调用。

 

    但是我一直没有想过session是否一定会被创建,这个创建具体是在什么时候,今天写了一段代码。想做个异想天开的实验,就是用户请求的时候再后台创建GUI界面可视化管理前台用户。这时候想到的是用session创建事件管理,但是没想到则么测试也不行,最后查询API发现,session并不是一定被创建。

 HttpSession getSession ()
          Returns the current session associated with this request, or if the request does not have a session, creates one.
 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.

    getSession有这两个方法。

 

    第一个就是默认在没有session的时候新建(new)一个session,第二个方法就是指定布尔型(boolean)确定是否创建session。第二个方法要注意的是。

<!-- Generated by javadoc (build 1.6.0_07) on Wed Jun 24 15:16:29 PDT 2009 -->

<noscript></noscript>

HttpSession


 getSession


(boolean create)

Returns the current HttpSession associated with this request or, if there is no current session and createis 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()

粗体字示意说:如果create参数传入false,并且request范围内没有 HttpSession对象,则此方法会返回null




由此看来,必须在调用getSession() 的时候才能创建session否则默认是不存在session的。



天行健君子以自强不息。
原文地址:https://www.cnblogs.com/mrye/p/java.html