关于request.getSession(true/false/null)的区别

关于request.getSession(true/false/null)的区别

一、需求原因

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

HttpSession session = request.getSession();

HttpSession session = request.getSession(true);

HttpSession session = request.getSession(false);

二、区别

1.      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 ifthere's no current session 
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session 

2.      翻译过来的意思是:

getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null; 
简而言之: 
HttpServletRequest.getSession(ture)等同于 HttpServletRequest.getSession() 
HttpServletRequest.getSession(false)等同于 如果当前Session没有就为null; 

3.      使用

当向Session中存取登录信息时,一般建议:HttpSession session =request.getSession();

当从Session中获取登录信息时,一般建议:HttpSession session =request.getSession(false);

4.      更简洁的方式

如果你的项目中使用到了spring(当然大点的项目都用到了),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequestrequest, String name)方法,看看源码:

publicstatic Object getSessionAttribute(HttpServletRequest request, String name){  

Assert.notNull(request, "Request must not be null");  

HttpSession session =request.getSession(false);  

return (session != null ?session.getAttribute(name) : null);  

}

注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常

你使用时:WebUtils.setSessionAttribute(request, “user”, User);

        User user = (User)WebUtils.getSessionAttribute(request, “user”);

三、运行结果

以上例子均测试验证通过。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值