温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java 中的true、false、null有何不同

发布时间:2020-11-10 15:47:53 来源:亿速云 阅读:343 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关java 中的true、false、null有何不同,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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

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是否为空,若为空就抛异常

你使用时:

WebUtils.setSessionAttribute(request, "user", User);

User user = (User)WebUtils.getSessionAttribute(request, "user");

关于java 中的true、false、null有何不同就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI