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或前台参数什么的。
"不要轻易把伤口揭开给别人看,因为别人看的是热闹,而痛的却是自己。"
原文地址:https://www.cnblogs.com/yanggb/p/11156965.html
时间: 2024-10-10 03:44:56