在很多时候,我们想要在一个普通类上面获取到request和response对象,这时候我们就要用到本地线程了
先创建一个本地线程线程,然后提供get和set方法。这时候我们就可以利用拦截器来把request和response对象存储到本地线程里面去了,只要存储好之后在任何地方都能获取到这个本地线程。
废话不多说,直接上代码。
package com.yxun8.utils;
?
import javax.servlet.http.HttpServletRequest;
?
/**
 * 创建本地线程
 */
public class RequestUtil {
    private static ThreadLocal<HttpServletRequest> local = new ThreadLocal();
?
    public static HttpServletRequest getLocal() {
        return local.get();
    }
?
    public static void setLocal(HttpServletRequest request){
        local.set(request);
    }
?
}
本地线程创建好了之后利用拦截器获取到request和response量大对象,再把它们存储进去
package com.yxun8.interceptor;
?
import com.yxun8.utils.RequestUtil;
import org.springframework.web.servlet.HandlerInterceptor;
?
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
public class MyInterceptor implements HandlerInterceptor {
?
    
在任意普通类把存储好的对象取出来
public class SystemAspect {
    public void log(){
       
        //把本地线程取出来
        HttpServletRequest request = RequestUtil.getLocal();
        
    }
}
原文:https://www.cnblogs.com/yxun8/p/13628301.html