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


目录
相关文章
|
SQL 人工智能 分布式计算
基于阿里云PAI平台搭建知识库检索增强的大模型对话系统
基于原始的阿里云计算平台产技文档,搭建一套基于大模型检索增强答疑机器人。本方案已在阿里云线上多个场景落地,将覆盖阿里云官方答疑群聊、研发答疑机器人、钉钉技术服务助手等。线上工单拦截率提升10+%,答疑采纳率70+%,显著提升答疑效率。
|
存储 安全 前端开发
SpringBoot整合Spring Security + JWT实现用户认证
SpringBoot整合Spring Security + JWT实现用户认证的实现
6881 2
SpringBoot整合Spring Security + JWT实现用户认证
|
关系型数据库 MySQL Docker
6. 修改docker端口 (映射宿主机和docker容器中的端口)
6. 修改docker端口 (映射宿主机和docker容器中的端口)
3246 0
6. 修改docker端口 (映射宿主机和docker容器中的端口)
|
4月前
|
人工智能 安全 网络安全
Burp Suite Professional 2025.5 for Windows x64 - 领先的 Web 渗透测试软件
Burp Suite Professional 2025.5 for Windows x64 - 领先的 Web 渗透测试软件
205 4
Burp Suite Professional 2025.5 for Windows x64 - 领先的 Web 渗透测试软件
|
4月前
|
Python
Python 中__new__方法详解及使用
`__new__` 是 Python 中的一个特殊方法,用于控制对象的创建过程,在 `__init__` 之前执行。它是类的静态方法,负责返回一个实例。如果 `__new__` 不返回对象,`__init__` 将不会被调用。本文详细介绍了 `__new__` 的作用、特性及与 `__init__` 的区别,并通过实例演示了其在单例模式中的应用,同时对比了 Python2 和 Python3 中的写法差异。
149 0
|
前端开发
Element UI 【实战】纯前端对表格数据进行增删改查(内含弹窗表单、数据校验、时间日期格式)
Element UI 【实战】纯前端对表格数据进行增删改查(内含弹窗表单、数据校验、时间日期格式)
432 6
|
10月前
|
弹性计算 Kubernetes Perl
k8s 设置pod 的cpu 和内存
在 Kubernetes (k8s) 中,设置 Pod 的 CPU 和内存资源限制和请求是非常重要的,因为这有助于确保集群资源的合理分配和有效利用。你可以通过定义 Pod 的 `resources` 字段来设置这些限制。 以下是一个示例 YAML 文件,展示了如何为一个 Pod 设置 CPU 和内存资源请求(requests)和限制(limits): ```yaml apiVersion: v1 kind: Pod metadata: name: example-pod spec: containers: - name: example-container image:
1289 2
|
安全 Linux 数据安全/隐私保护
忘记CentOS 7.7 root密码?别慌,一招教你轻松解决!
对于系统管理员来说,密码是保护系统安全的第一道防线。但在实际操作中,忘记密码的情况难以避免。如果忘记了CentOS 7.7的root密码,可能会无法执行一些需要root权限的重要操作,因此学会如何在忘记密码后重置变得尤为重要。
忘记CentOS 7.7 root密码?别慌,一招教你轻松解决!
|
JavaScript Java 测试技术
基于springboot+vue.js的大学生就业需求分析系统附带文章和源代码设计说明文档ppt
基于springboot+vue.js的大学生就业需求分析系统附带文章和源代码设计说明文档ppt
150 1
|
人工智能 自然语言处理 IDE
通义灵码:程序员必备的AI编程助手!
通义灵码:阿里云AI编程助手,提供代码生成、智能问答、异常排查等功能,支持多种编程语言和IDE,如VSCode、JetBrains。具备跨文件感知、阿里云服务优化,现个人专业版限时免费。包括行级/函数级续写、自然语言转代码、单元测试生成、代码优化与注释、研发问答等。适用于Java、Python等语言
1296 0