HttpSession session = request.getSession(false); HttpSession session = request.getSession(true); HttpSession session = request.getSession(); 这三种分别什么意思getSession是返回当前用户的会话对象,参数的区别在于 参数为true,则如果“当前用户的会话对象”为空(第一次访问时)则创建一个新的会话对象返回 参数为false,则如果“当前用户的会话对象”为空,则返回null(即不自动创建会话对象) 注意request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则请尽量使用request.getSession(false)。
关于HttpServletRequest接口的getSession方法,在页面提交请求到servlet时,用getSession(false)返回的却是一个session对象而不是null的问题。
getSession有两种方法,一个有参的、一个是无参的。
getSession()与getSession(true)一样,获取request对象关联的session对象,如果没有session,则返回一个新的session。
getSession(false)也是返回一个request对象关联的session对象,但如果没有session,则返回null。
Java EE 5 API中的定义:
HttpSession getSession(boolean create)
-
Returns the current
HttpSession
associated with this request or, if there is no current session andcreate
is true, returns a new session. -
If
create
isfalse
and the request has no validHttpSession
, this method returnsnull
.
在Jsp页面提交表单到servlet时,在servlet中调用getSession(false)时却返回了一个session,而不是null。
原因是Jsp页面会默认创建session对象,即<@page session="true">,默认是true,如果手动将session设为false,则jsp不会创建session对象,页面也就不可以直接使用session对象。这样提交到servlet,用方法getSession(false)返回的就是null。