概述
springmvc中requestcontextholder获取请求信息
requestcontextholder的作用是:
在service层获取获取request和response信息
代码示例:
servletrequestattributes attrs = (servletrequestattributes)requestcontextholder.getrequestattributes();
httpservletrequest request = attrs.getrequest();
源码分析:
定义了两个threadlocal变量用来存储request
private static final threadlocal requestattributesholder = new namedthreadlocal("request attributes");
private static final threadlocal 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;
}
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
最后
以上就是标致小懒猪为你收集整理的java中holder_SpringMVC中RequestContextHolder获取请求信息的全部内容,希望文章能够帮你解决java中holder_SpringMVC中RequestContextHolder获取请求信息所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复