HttpServletRequest:Get Session

简介: 接口HttpServletRequest继承自ServletRequest。

1. HttpServletRequest.getSession

1.1 HttpServletRequest

接口HttpServletRequest继承自ServletRequest。

HttpServletRequest extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.—— From javadoc

客户端浏览器发出的请求,会被封装成为一个HttpServletRequest对象。

请求的所有的信息,包括请求的地址、请求的参数、提交的数据、上传的文件、客户端的ip,甚至客户端操作系统都包含在其内。

servlet容器会创建一个HttpServletRequest对象,并将其转换为servlet的service、doGet、 doPost等方法的参数。

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).—— From javadoc

与Request相对的,HttpServletResponse继承了ServletResponse接口,并提供了与Http协议有关的方法,这些方法的主要功能是设置HTTP状态码和管理Cookie等。

1.2 getSession

HttpServletRequest 提供了两个重载的getSession方法,分别是getSession()和getSession(boolean create)。

getSession()和getSession(true)是相同的,都是获取当前客户端的Session,如果获取不到则创建一个新的Session返回。

getSession(false),也是获取当前客户端的Session,不同的是,如果获取不到则返回null。

getSession
  HttpSession getSession()
    Gets the HttpSession connected with the client sending the request. If the client didn't have a session connected with him then a new HttpSession will be created. To maintain a session this method must be called before the connection is flushed or closed. Same as calling getSession(true).
  Returns:
    The HttpSession connected with the client sending the request.
  Since:2.1getSession
  HttpSession getSession(boolean create)
    Gets the HttpSession connected with the client sending the request. If the client didn't have a session connected with him, and create is true then a new HttpSession will be created. If create is false then null is returned. To maintain a session this method must be called before the connection is flushed or closed.
  Returns:
    The HttpSession connected with the client sending the request.
  Since:2.0
—— From javadoc

1.3 getSession() VS. getSession(boolean create)

在大多数场景下,getSession方法的目的是获取当前请求客户端的Session,然后设置或者获取属性。

如果获取不到当前请求客户端的Session,那么重新创建一个Session,一般情况下意义不大,纯属浪费。

因此推荐使用getSession(false)的方式来获取Session,注意先判空再使用即可,下面会详细介绍。

2. springmvc-session.xml

2.1 SessionUtil

通常从Session里存取属性的代码如下:

HttpSession session=request.getSession(false);
session.setAttribute("bar", new Long("1024"));
Object foo=session.getAttribute("foo");

可以抽取为工具类SessionUtil:

public final class SessionUtil{
  public static void setAttribute(HttpServletRequest request,String attributeName,Serializable attributeValue){
    request.getSession().setAttribute(attributeName, attributeValue);
  }
  public static <T> T getAttribute(HttpServletRequest request,String attributeName){
      Validate.notNull(request, "request can't be null!");
      HttpSession session = request.getSession(false);
      return session == null ? null : (T) session.getAttribute(attributeName);
  }
}

2.2 SessionAccessor

为了便于统一管理Session,可以将存取Session属性统一配置在XML中,实现和使用方式如下。

  • SessionUtil
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public final class SessionUtil{
    public static <T> T getAttribute(HttpServletRequest request,String attributeName){
        HttpSession session = request.getSession(false);
        return session == null ? null : (T) session.getAttribute(attributeName);
    }
    public static void setAttribute(HttpServletRequest request,String attributeName,Serializable attributeValue){
        request.getSession().setAttribute(attributeName, attributeValue);
    }
    public static void removeAttribute(HttpServletRequest request,String attributeName){
        HttpSession session = request.getSession(false);
        if (null == session){
            return;
        }
        session.removeAttribute(attributeName);
    }
    /**
     * 遍历session的attribute,将 name /attributeValue 存入到map里.
     */
    public static Map<String, Serializable> getAttributeMap(HttpSession session){
        Map<String, Serializable> map = new HashMap<String, Serializable>();
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()){
            String name = attributeNames.nextElement();
            map.put(name, (Serializable) session.getAttribute(name));
        }
        return map;
    }
    private SessionUtil(){
        throw new AssertionError("can not creat " + getClass().getName() + " instance");
    }
}
  • Accessible
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
public interface Accessible{
    public void save(String key,Serializable serializable,HttpServletRequest request);
    public <T extends Serializable> T get(String key,HttpServletRequest request);
    public void remove(String key,HttpServletRequest request);
}
  • AbstractSessionAccessor
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import com.feilong.servlet.http.SessionUtil;
public class AbstractSessionAccessor implements Accessible{
    @Override
    public void save(String key,Serializable serializable,HttpServletRequest request){
        SessionUtil.setAttribute(request, key, serializable);
    }
    @Override
    public <T extends Serializable> T get(String key,HttpServletRequest request){
        return SessionUtil.getAttribute(request, key);
    }
    @Override
    public void remove(String key,HttpServletRequest request){
        SessionUtil.removeAttribute(request, key);
    }
}
  • SessionAccessor
package demo.session;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
public class SessionAccessor extends AbstractSessionAccessor{
    private String key;
    public void save(Serializable serializable,HttpServletRequest request){
        super.save(key, serializable, request);
    }
    public <T extends Serializable> T get(HttpServletRequest request){
        return super.get(key, request);
    }
    public void remove(HttpServletRequest request){
        super.remove(key, request);
    }
    public SessionAccessor(){}
    public SessionAccessor(String key){
        this.key = key;
    }
    public void setKey(String key){
        this.key = key;
    }
    public String getKey(){
        return key;
    }
}
  • springmvc-session.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        ">
    <bean name="fooSessionAccessor" class="demo.session.SessionAccessor">
        <property name="key" value="attr_name_foo" />
    </bean>
</beans>
  • FooController
@Controller
public class FooController extends BaseController{
    @Autowired
    @Qualifier("fooSessionAccessor")
    private SessionAccessor fooSessionAccessor;
    @ResponseBody
    @RequestMapping(value = "/root/path/foo",method = RequestMethod.POST)
        public Object foo(HttpServletRequest request,HttpServletResponse response){
        guestKeySessionAccessor.save("value1", request);
        guestKeySessionAccessor.get(request);
        guestKeySessionAccessor.remove(request);
     }
}

参考链接

搜狗百科 - httpservletrequest

GNU-javadoc-HttpServletRequest


目录
相关文章
解决开启子线程,导致request上下文和session信息丢失问题
解决开启子线程,导致request上下文和session信息丢失问题
1743 0
|
Shell Linux API
【Shell 命令集合 文件管理】Linux 移动文件命令 mv命令使用指南
【Shell 命令集合 文件管理】Linux 移动文件命令 mv命令使用指南
1443 0
|
6月前
|
Ubuntu Linux KVM
虚拟机使用教程大全(一)
教程来源 https://tmywi.cn/ 虚拟机技术已成IT从业者必备技能。本文聚焦“使用”而非搭建,涵盖资源调优、网络配置、快照备份、性能监控与故障排查等30+实用章节,兼容VMware/VirtualBox/KVM,含100+命令示例与实战技巧。
|
人工智能 安全 Java
SpringBoot配置文件的12个实用技巧
本文介绍了SpringBoot配置的核心功能与最佳实践,涵盖多环境配置、属性优先级、松散绑定、随机值生成、类型安全配置、敏感信息加密、占位符使用、条件化加载、复杂数据结构配置及元数据支持等内容。通过合理运用这些特性,开发者可以提高应用的灵活性、可维护性和安全性,满足不同场景下的需求。文章结合具体示例,帮助读者深入理解并掌握SpringBoot配置的高级用法。
567 1
|
Linux 编译器 测试技术
【C++】CentOS环境搭建-快速升级G++版本
通过上述任一方法,您都可以在CentOS环境中高效地升级G++至所需的最新版本,进而利用C++的新特性,提升开发效率和代码质量。
1096 64
|
XML JSON 前端开发
HTTP协议,Content-Type格式介绍篇
通过理解和正确使用Content-Type头字段,可以确保数据在网络上传输时的正确性和高效性,提升网络应用的可靠性和用户体验。
1967 18
|
前端开发 Java Spring
@RequestMapping, @GetMapping, 和 @PostMapping区别
@RequestMapping, @GetMapping, 和 @PostMapping区别
|
Java 关系型数据库 API
使用Spring Boot和PostgreSQL构建高级查询
使用Spring Boot和PostgreSQL构建高级查询
|
JavaScript 前端开发
基于Vue实现具有固定表头、合并单元格的Html表格
本文介绍了如何在Vue框架中创建一个具有固定表头和合并单元格功能的HTML表格,通过CSS的`position: sticky`属性实现表头固定,并通过设置`rowspan`和`colspan`属性来实现单元格合并。
675 0
基于Vue实现具有固定表头、合并单元格的Html表格
|
存储 前端开发 Java
若依修改----数据字典,可以用于维护系统中常见的静态数据,为什么不写死,用字典维护?数据字典的好处是一个地方编写数据,在多个地方,复用他,静态选项这里填完,换其他,用户性别这里的男女,就转成而来字典
若依修改----数据字典,可以用于维护系统中常见的静态数据,为什么不写死,用字典维护?数据字典的好处是一个地方编写数据,在多个地方,复用他,静态选项这里填完,换其他,用户性别这里的男女,就转成而来字典

热门文章

最新文章