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();
    }
}
相关推荐
q***318320 小时前
Spring Boot(快速上手)
java·spring boot·后端
q***098020 小时前
Spring Boot 3.3.4 升级导致 Logback 之前回滚策略配置不兼容问题解决
java·spring boot·logback
q***098020 小时前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
羊锦磊21 小时前
[ 项目开发 1.0 ] 新闻网站的开发流程和注意事项
java·数据库·spring boot·redis·spring·oracle·json
吴名氏.21 小时前
电子书《21天学通Java(第5版)》
java·开发语言·21天学通java
ruleslol21 小时前
SpringBoot面试题09-SpringBoot启动流程
spring boot
曼巴UE521 小时前
UE5 C++ JSON 最简单,麻烦的方式,直接读存(一)
java·服务器·前端
QMY5205201 天前
什么是爬虫?
java·eclipse
bbq粉刷匠1 天前
力扣--两数之和(Java)
java·leetcode