HttpServletRequest接口的getSession方法

来源:互联网 发布:js base64转换成file 编辑:程序博客网 时间:2024/05/16 17:38
关于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 and create is true, returns a new session.
If 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。

原创粉丝点击