Spring / Spring Boot全局获取HttpServletRequest、HttpServletResponse对象

1.前言

你还在 Controller 传一个 HttpServletRequest 或 HttpServletResponse 到下面好几层以便获取到该对象进行处理吗??

那就 out 咯,曾经我也是这么做的,哈哈哈~

今天写代码想起来要获取这个对象,一下子想不起来叫什么了,只隐隐约约记得叫 HttpRequestContextHolder 来获取,但是,错了,其实是RequestContextHolder,难怪自动提示来不出来。

于是,我决定还是写个文章记录一下方便以后自己找

2.代码

java 复制代码
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
HttpServletResponse response = requestAttributes.getResponse();

比如你也可以稍微封装一下,搞一个类静态调用分别获取 Request、Response,随后你就可以在项目的任何位置调用得到这两个对象以便在请求前、返回前做一些别的处理了。

这里,我只是举个例子:

java 复制代码
public class MyServletContextHolder {

    private static ServletRequestAttributes requestAttributes = null;


    private static void lazyInit() {
        if (null == requestAttributes) {
            synchronized (MyServletContextHolder.class) {
                if (null == requestAttributes) {
                    requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                }
            }
        }
    }


    public static HttpServletRequest getHttpServletRequest() {
        lazyInit();
        return requestAttributes.getRequest();
    }


    public static HttpServletResponse getHttpServletResponse() {
        lazyInit();
        return requestAttributes.getResponse();
    }
}
相关推荐
学习3人组12 分钟前
JVM GC长暂停问题排查
java
R_AirMan24 分钟前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
人生在勤,不索何获-白大侠43 分钟前
day17——Java集合进阶(Collections、Map)
java·开发语言
程序员小羊!1 小时前
Java教程:JavaWeb ---MySQL高级
java·开发语言·mysql
白仑色1 小时前
Spring Boot 多环境配置详解
java·spring boot·后端·微服务架构·配置管理
超级小忍1 小时前
在 Spring Boot 中优化长轮询(Long Polling)连接频繁建立销毁问题
java·spring boot·后端
David爱编程1 小时前
Java 中 Integer 为什么不是万能的 int 替代品?
java·后端
老马啸西风1 小时前
个人网站一键引入免费开关评论功能 giscus
java
Z_W_H_2 小时前
【springboot】IDEA手动创建SpringBoot简单工程(无插件)
java·spring boot·intellij-idea
HeXDev2 小时前
【SkyWalking】服务端部署与微服务无侵入接入实战指南
java·微服务·架构·skywalking·链路追踪·微服务治理