1.问题描述:
在使用ServletUtils工具类中的静态方法获取request对象时,在controller层可以获取到,在service实现类中无法获取。
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
2.原因分析:
controller层开启了多线程。(开启多线程之前可以获取到,开启之后在子线程中无法获取)原因是request 信息是存储在 ThreadLocal 中的,所以子线程根本无法获取到主线程的 request 信息。
//创建线程对象
private void createThead(String key) throws Exception {
Thread thread = new Thread(new getKey(key));
thread.start();
}
//开启线程
private class getKey implements Runnable{
private Key key;
public getKey(Key key) {
this.key = key;
}
//Runnable接口中的抽象方法
public void run() {
try {
getKey(key);
} catch (Exception e) {
System.out.println(e);
}
}
}
3.解决方法:
在新开子线程之前增加两行代码,将RequestAttributes对象设置为子线程共享。
//创建线程对象
private void createThead(String key) throws Exception {
//将RequestAttributes对象设置为子线程共享
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(sra, true);
Thread thread = new Thread(new getKey(key));
thread.start();
}