码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-09-02 09:51:10      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:返回   http   cookies   意思   Servle   rop   gets   round   returns   

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或前台参数什么的。

 

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

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

标签:返回   http   cookies   意思   Servle   rop   gets   round   returns   

原文地址:https://www.cnblogs.com/yanggb/p/11156965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!