ThreadLocal
https://www.jianshu.com/p/3c5d7f09dfbd
在springboot中service层需要得到request有应用到它
//HttpServletRequest对象代表客户端的请求
//最近遇到的问题是在service获取request和response,正常来说在service层是没有request的,然而直接从controlller传过来的话解决方法太粗暴
//RequestContextHolder顾名思义,持有上下文的Request容器
//RequestContextHolder这个类,里面有两个ThreadLocal保存当前线程下的request
//`getRequestAttributes()`方法,相当于直接获取ThreadLocal里面的值,这样就保证了每一次获取到的Request是该请求的request.
//获得request请求
protected HttpServletRequest getRequest(){
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
网友评论