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/archive/2011/11/15/java.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值