(转)request.getSession()几种获取情况之间的差异

一、三种情况

 

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

 

 

二、三种情况之间的差异

  getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null; 

  简而言之: 

  HttpServletRequest.getSession(ture)等同于 :HttpServletRequest.getSession() ,若存在会话则返回该会话,否则创建一个新的会话Session

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

  

三、具体的使用场景

  当向Session中存入登录信息时,一般建议:HttpSession session =request.getSession();

  当从Session中获取登录信息时,一般建议:HttpSession session =request.getSession(false);

 

四、更简洁的方式

  如果你的项目中使用到了Spring(当然大点的项目都用到了),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequestrequest, String name)方法,看看源码:

publicstatic 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);
}

  注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常

  你使用时:WebUtils.setSessionAttribute(request, “user”, User);

              User user = (User)WebUtils.getSessionAttribute(request, “user”);

  源码:

 

 

复制代码
/**
 * Set the session attribute with the given name to the given value.
 * Removes the session attribute if value is null, if a session existed at all.
 * Does not create a new session if not necessary!
 * @param request current HTTP request
 * @param name the name of the session attribute
 */
public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
  if (value != null) {
    request.getSession().setAttribute(name, value);
  } else {
    HttpSession session = request.getSession(false);
    if (session != null) {
      session.removeAttribute(name);
    }
  }
}
复制代码

 

posted @   沧海一粟hr  阅读(2035)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示