获取当前线程中的HttpServletRequest对象
1、使用spring注解自动注入也是线程安全
参考:
https://blog.csdn.net/xiaoguangtouqiang/article/details/80885270?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165615329416781818729269%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165615329416781818729269&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-80885270-null-null.nonecase&utm_term=Spring%E8%8E%B7%E5%8F%96HttpServletRequest&spm=1018.2226.3001.4450
@Autowired private HttpServletRequest httpServletRequest;
1.1 通过接口调用处理的类使用其获取参数是正常的
1.2 如果是通过spring的监听或者定时任务发起的请求HttpServletRequest不为空,但是使用其获取参数的时候 62行会抛出异常(原因是@Autowired注入的是代理类每次执行时会从当前线程获取具体的对象,但是定时任务发起的请求没有HttpServletRequest所以校验报错)
org.springframework.web.context.request.RequestContextHolder#currentRequestAttributes
2、提取内部获取逻辑自己实现的工具类避免报错的问题
package com.hdx.common.hdxspringinit.utils;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Controller
public class HttpServerletRequestUtils {
/**
* 获取当前线程HttpServletRequest对象
*
* @return HttpServletRequest
*/
public HttpServletRequest getServerRequest(){
HttpServletRequest httpServletRequest = null;
try {
RequestAttributes requestattributes = RequestContextHolder.getRequestAttributes();
if (requestattributes == null) {
return null;
}
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestattributes;
if (servletRequestAttributes == null) {
return null;
}
httpServletRequest = servletRequestAttributes.getRequest();
} catch (Exception exception) {
// 打印异常信息
exception.printStackTrace();
}
return httpServletRequest;
}
}