zoukankan      html  css  js  c++  java
  • request.getSession(true)和request.getSession(false)的区别

    request.getSession(true):若存在会话则返回该会话,否则新建一个会话。

    request.getSession(false):若存在会话则返回该会话,否则返回NULL。

    三种重载方法

    现实中我们经常会遇到以下3种用法:

    HttpSession session = request.getSession();
    HttpSession session = request.getSession(true);
    HttpSession session = request.getSession(false);

    三种重载方法的区别

    Servlet官方文档的说明:

    public HttpSessiongetSession(boolean create) 
    
    Returns the currentHttpSession associated with this request or, if if there is no current sessionand create is true, returns a new session. 
    If create is falseand the request has no valid HttpSession, this method returns null. 
    To make sure thesession is properly maintained, you must call this method before the responseis committed. If the container is using cookies to maintain session integrityand is asked to create a new session when the response is committed, anIllegalStateException 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: theHttpSession associated with this request or null if create is false and therequest has no valid session.

    翻译过来的意思就是:getSession(boolean create)是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession为null,当create为true,就创建一个新的Session;当create为false,则返回null。create的默认值为true,即这里的HttpServletRequest.getSession(ture)等同于HttpServletRequest.getSession()。

    根据这个特性,在使用上,当向Session中存取登录信息时,一般建议使用request.getSession()/request.getSession(true);当从Session中只获取登录信息时,一般建议使用request.getSession(false)。

    当然了,现在各种Web框架都会封装一些方便存取Session的工具类,一般是不建议直接从request中获取Session或前台参数什么的。

    "不要轻易把伤口揭开给别人看,因为别人看的是热闹,而痛的却是自己。"

  • 相关阅读:
    在未排序的数组中找到第 k 个最大的元素
    区域和检索
    控制台画图程序(可更换笔刷版本)
    循环中的scanf处理了换行符怎么破
    strlen获取字符数组为什么是255
    宽字符输出中文,Devc++解决方法
    区间取最小值最大值-位值和
    模拟鼠标键盘-封装函数
    scanf("%d",a[i]+j)为什么不加取地址符号
    scanf需要多输入一行是什么问题
  • 原文地址:https://www.cnblogs.com/yanggb/p/11156965.html
Copyright © 2011-2022 走看看