gpt4 book ai didi

java 中 request.getSession(true、false、null)的区别

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 26 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章java 中 request.getSession(true、false、null)的区别由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

java 中 request.getSession(true/false/null)的区别 。

1、需求原因 。

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

HttpSession session = request.getSession(),

HttpSession session = request.getSession(true),

HttpSession session = request.getSession(false),

2、区别 。

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; 。

简而言之:

?
1
2
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)的WebUtils.getSessionAttribute(HttpServletRequestrequest, String name);方法,看看源码:

?
1
2
3
4
5
6
7
8
9
public static 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是否为空,若为空就抛异常 。

你使用时:

?
1
2
3
4
WebUtils.setSessionAttribute(request, "user" , User);
 
User user = (User)WebUtils.getSessionAttribute(request, "user" );
<br>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! 。

原文链接:https://my.oschina.net/anxiaole/blog/840890 。

最后此篇关于java 中 request.getSession(true、false、null)的区别的文章就讲到这里了,如果你想了解更多关于java 中 request.getSession(true、false、null)的区别的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com