欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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;
    }