【转】HttpServletRequest接口的getSession方法

本文解析了HttpServletRequest接口中getSession(false)方法的行为。此方法旨在返回与请求关联的HttpSession对象,若不存在则返回null。文章深入探讨了JSP页面如何影响getSession(false)的返回值,并解释了如何通过设置<@pagesession=false>来避免自动创建session。

关于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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值