关于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)
HttpSession
associated with this request or, if there is no current session and
create
is true, returns a new session.
create
is
false
and the request has no valid
HttpSession
, this method returns
null
.
在Jsp页面提交表单到servlet时,在servlet中调用getSession(false)时却返回了一个session,而不是null。
原因是Jsp页面会默认创建session对象,即<@page session="true">,默认是true,如果手动将session设为false,则jsp不会创建session对象,页面也就不可以直接使用session对象。这样提交到servlet,用方法getSession(false)返回的就是null。
原帖地址:http://blog.csdn.net/wing32/article/details/5618106