request.getSession(true)和request.getSession(false)的区别

request.getSession(true):若存在会话则返回该会话,否则新建一个会话。

request.getSession(false):若存在会话则返回该会话,否则返回NULL。

三种重载方法

现实中我们经常会遇到以下3种用法:

HttpSession session = request.getSession();
HttpSession session = request.getSession(true);
HttpSession session = request.getSession(false);

三种重载方法的区别

Servlet官方文档的说明:

public HttpSessiongetSession(boolean create) 

Returns the currentHttpSession associated with this request or, if if there is no current sessionand create is true, returns a new session. 
If create is falseand the request has no valid HttpSession, this method returns null. 
To make sure thesession is properly maintained, you must call this method before the responseis committed. If the container is using cookies to maintain session integrityand is asked to create a new session when the response is committed, anIllegalStateException is thrown. 
Parameters: true -to create a new session for this request if necessary; false to return null if there's no current session.
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session.

翻译过来的意思就是:getSession(boolean create)是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession为null,当create为true,就创建一个新的Session;当create为false,则返回null。create的默认值为true,即这里的HttpServletRequest.getSession(ture)等同于HttpServletRequest.getSession()。

根据这个特性,在使用上,当向Session中存取登录信息时,一般建议使用request.getSession()/request.getSession(true);当从Session中只获取登录信息时,一般建议使用request.getSession(false)。

当然了,现在各种Web框架都会封装一些方便存取Session的工具类,一般是不建议直接从request中获取Session或前台参数什么的。

 

"不要轻易把伤口揭开给别人看,因为别人看的是热闹,而痛的却是自己。"

转载于:https://www.cnblogs.com/yanggb/p/11156965.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值