java 中 request.getSession(true、false、null)的区别
java中request.getSession(true/false/null)的区别
一、需求原因
现实中我们经常会遇到以下3中用法:
HttpSessionsession=request.getSession();
HttpSessionsession=request.getSession(true);
HttpSessionsession=request.getSession(false);
二、区别
1. Servlet官方文档说:
publicHttpSessiongetSession(booleancreate)
ReturnsthecurrentHttpSessionassociatedwiththisrequestor,ififthereisnocurrentsessionandcreateistrue,returnsanewsession.
IfcreateisfalseandtherequesthasnovalidHttpSession,thismethodreturnsnull.
Tomakesurethesessionisproperlymaintained,youmustcallthismethodbeforetheresponseiscommitted.IftheContainerisusingcookiestomaintainsessionintegrityandisaskedtocreateanewsessionwhentheresponseiscommitted,anIllegalStateExceptionisthrown.
Parameters:true-tocreateanewsessionforthisrequestifnecessary;falsetoreturnnullifthere'snocurrentsession
Returns:theHttpSessionassociatedwiththisrequestornullifcreateisfalseandtherequesthasnovalidsession
2. 翻译过来的意思是:
getSession(booleancreate)意思是返回当前reqeust中的HttpSession,如果当前reqeust中的HttpSession为null,当create为true,就创建一个新的Session,否则返回null;
简而言之:
HttpServletRequest.getSession(ture)等同于HttpServletRequest.getSession() HttpServletRequest.getSession(false)等同于如果当前Session没有就为null;
3. 使用
当向Session中存取登录信息时,一般建议:HttpSessionsession=request.getSession();
当从Session中获取登录信息时,一般建议:HttpSessionsession=request.getSession(false);
4. 更简洁的方式
如果你的项目中使用到了Spring,对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的WebUtils.getSessionAttribute(HttpServletRequestrequest,Stringname);方法,看看源码:
publicstaticObjectgetSessionAttribute(HttpServletRequestrequest,Stringname){ Assert.notNull(request,"Requestmustnotbenull"); HttpSessionsession=request.getSession(false); return(session!=null?session.getAttribute(name):null); }
注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常
你使用时:
WebUtils.setSessionAttribute(request,"user",User); Useruser=(User)WebUtils.getSessionAttribute(request,"user");
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!