SpringMVC中RequestContextHolder获取请求信息
程序员文章站
2022-06-22 21:42:35
SpringMVC中RequestContextHolder获取请求信息 RequestContextHolder的作用是: 在Service层获取获取request和response信息 代码示例: 源码分析: 定义了两个ThreadLocal变量用来存储Request 设置方法 是在Spri ......
springmvc中requestcontextholder获取请求信息
requestcontextholder的作用是:
在service层获取获取request和response信息
代码示例:
servletrequestattributes attrs = (servletrequestattributes)requestcontextholder.getrequestattributes(); httpservletrequest request = attrs.getrequest();
源码分析:
定义了两个threadlocal变量用来存储request
private static final threadlocal<requestattributes> requestattributesholder = new namedthreadlocal("request attributes"); private static final threadlocal<requestattributes> inheritablerequestattributesholder = new namedinheritablethreadlocal("request context");
设置方法
public static void setrequestattributes(@nullable requestattributes attributes) { setrequestattributes(attributes, false); } public static void setrequestattributes(@nullable requestattributes attributes, boolean inheritable) { if (attributes == null) { resetrequestattributes(); } else if (inheritable) { inheritablerequestattributesholder.set(attributes); requestattributesholder.remove(); } else { requestattributesholder.set(attributes); inheritablerequestattributesholder.remove(); } }
是在springmvc处理servlet的类frameworkservlet的类中,doget/dopost方法,调用processrequest方法进行初始化上下文方法中initcontextholders设置进去的
private void initcontextholders(httpservletrequest request, @nullable localecontext localecontext, @nullable requestattributes requestattributes) { if (localecontext != null) { localecontextholder.setlocalecontext(localecontext, this.threadcontextinheritable); } if (requestattributes != null) { requestcontextholder.setrequestattributes(requestattributes, this.threadcontextinheritable); } if (this.logger.istraceenabled()) { this.logger.trace("bound request context to thread: " + request); } }
再看一下请求信息怎么获取
@nullable public static requestattributes getrequestattributes() { requestattributes attributes = (requestattributes)requestattributesholder.get(); if (attributes == null) { attributes = (requestattributes)inheritablerequestattributesholder.get(); } return attributes; }
推荐阅读
-
获取MSSQL 表结构中字段的备注、主键等信息的sql
-
完整删除ecshop中获取店铺信息的API
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
详解Linux中几个获取硬件详细信息的命令
-
Android中获取apk安装包信息的方法
-
java通过HttpServletRequest获取post请求中的body内容的方法
-
springcloud 中 zuul 修改请求参数信息的方法
-
Oracle中获取会话信息的两个函数分享
-
jsp页面中获取servlet请求中的参数的办法详解
-
数据库SQL实战:获取所有部门中当前员工薪水最高的相关信息(教程)