servlet中的session不一定会被创建

参考:http://c5ms.iteye.com/blog/1260593

servlet中的session不一定会被创建


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

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

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


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

 

 HttpSessiongetSession() 
          Returns the current session associated with this request, or if the request does not have a session, creates one.
 HttpSessiongetSession(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 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 session
Returns:
the  HttpSession associated with this request or  null if  create is  false and the request has no valid session
See Also:
getSession()


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





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


呵呵,有什么不对的地方大家请指出,谢谢了。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值