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();
    }
}
相关推荐
choice of11 分钟前
SpringMVC通过注解实现全局异常处理
java·后端·spring
单线程bug11 分钟前
Spring Boot中Filter与Interceptor的区别
java·spring boot·后端
小蒜学长17 分钟前
基于uni-app的蛋糕订购小程序的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端·小程序·uni-app
GitCode官方19 分钟前
告别环境地狱!Java生态“AI原生”解决方案入驻 GitCode
java·开源·gitcode
东方芷兰1 小时前
Leetcode 刷题记录 21 —— 技巧
java·算法·leetcode·职场和发展·github·idea
麦麦大数据1 小时前
J002 Vue+SpringBoot电影推荐可视化系统|双协同过滤推荐算法评论情感分析spark数据分析|配套文档1.34万字
vue.js·spring boot·数据分析·spark·可视化·推荐算法
kyle~1 小时前
排序---选择排序(Selection Sort)
java·算法·排序算法
七夜zippoe4 小时前
事务方案选型全景图:金融与电商场景的实战差异与落地指南
java·分布式·事务
杨二K6 小时前
认识HertzBeat的第一天
java·hertzbeat
DevilSeagull6 小时前
JavaScript WebAPI 指南
java·开发语言·javascript·html·ecmascript·html5