request.getSession();

好多人都在用 request.getSession(); ,但是好多人都不知道他具体的用法,下面我来具体说明下:
1.官方提供的api的解释:
getSession
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if 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.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException 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: the HttpSession associated with this request or null if create is false and the request has no valid session
翻译过来是这样的:
getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;
简而言之:
HttpServletRequest.getSession(ture) 等同于 HttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;
2.举个最常见的列子:
// a new session created if no session exists, 哈哈!完蛋啦!如果session不存在的话你又创建了一个!HttpSession session = request.getSession(); String user_name = session.getAttribute(“user_name”);
需要注意的地方是request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则尽量使用request.getSession(false)。在使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:
HttpSession session = request.getSession(false);
if (session != null) {
String user_name = session.getAttribute(“user_name”);
}
3.其实Spring中也封装的得到 session 的方法:
在spring的项目中取值,可以用 WebUtils 工具,看看源码:
/**

  • Check the given request for a session attribute of the given name.
  • Returns null if there is no session or if the session has no such attribute.
  • Does not create a new session if none has existed before!
  • @param request current HTTP request
  • @param name the name of the session attribute
  • @return the value of the session attribute, or null if not found
    */
    public static Object getSessionAttribute(HttpServletRequest request, String name) {
    Assert.notNull(request, “Request must not be null”);
    HttpSession session = request.getSession(false);
    return (session != null ? session.getAttribute(name) : null);
    }
    上面的代码可以写成下面这个:
    HttpSession session = request.getSession(false);
    String user_name = WebUtils.getSessionAttribute(reqeust, “user_name”);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值