获取当前线程中的HttpServletRequest对象
作者:互联网
1、使用spring注解自动注入也是线程安全的参考了:https://mbd.baidu.com/ug_share/mbox/4a83aa9e65/share?product=smartapp&tk=9f5b9a1e513c2f82715d65bf455d2129&share_url=https%3A%2F%2Fyebd1h.smartapps.cn%2Fpages%2Fblog%2Findex%3FblogId%3D80885270%26_swebfr%3D1%26_swebFromHost%3Dbaiduboxapp&domain=mbd.baidu.com
@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;
}
}
标签:HttpServletRequest,web,springframework,获取,线程,import,org,null 来源: https://www.cnblogs.com/hu0529/p/16412167.html