RequestContextHolder获取HttpServletRequest 解决线程安全

  • Post author:
  • Post category:其他


昨天在在web项目中,出了 一个 问题,就是 之前 开发项目太赶了,而框架又是别人的框架 所以在获取 session的时候, 特别是 用户id 的时候,个别用户的 存入数据库里面 是 其他用户的 id 这个 user 是通过 session 获取的。 之前就听说了, request 是线程不安全的, session 有可能获取到别的用户的信息。 我还一直感觉不太可能,现在终于遇到这样的问题了。。。 这时候就需要使用 到 threadLocal 了 可以自己 封装, 也可以 使用 spring 的 RequestContextHolder 类,来结合使用。都是线程安全的

参考地址


参考地址

首先在web.xml中添加如下代码:

<listener>

      <listener-class>org.springframework.web.context.request.RequestContextListener<listener-class>

</listener>

可以在service方法中或普通类中使用此代码获取请求Request

HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();


具体可以自己封装了。。 可以自己 封装 threadLocal 了。 既然spring 自带了,感觉还是使用 自带的功能感觉比较 好 看个人喜好了 或者可以这样:


	protected static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();

	protected static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();
@ModelAttribute
	public void setReqAndRes(HttpServletRequest request,
			HttpServletResponse response) {
		this.request.set(request);
		this.response.set(response);
	}

转载于:https://my.oschina.net/ouminzy/blog/872551