ThreadLocal 在 servlet 中存储 ServletRequest 和 Response:有什么用? [英] ThreadLocal to store ServletRequest and Response in servlet: what for?

查看:19
本文介绍了ThreadLocal 在 servlet 中存储 ServletRequest 和 Response:有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一次我遇到了一种模式,其中 ServletRequest 和响应对象被放入 servlet 的本地 ThreadLocal 变量.servlet 类还有获取当前请求和响应对象的方法.所以为了得到这些对象,你还是需要对servlet对象进行操作.

Once I have came across a pattern, where ServletRequest and response objects are put to servlet's local ThreadLocal variables. The servlet class has also methods to get current request and response objects. So in order to get these objects you still need to operate with servlet object.

拥有这些 ThrealLocal 局部变量有什么意义?

What is the point of having these ThrealLocal local variables?

推荐答案

重点是在类中包含请求和响应对象,否则它们将不会包含它们(例如它们不是 servlet).一个例子是 JSF 托管 bean - 它们的方法不接受 HttpServletRequest 参数,因此您可以通过 FacesContext 获取请求,ThreadLocal 中包含它们代码>变量.

The point is to have the request and response objects in classes that would otherwise would not have them (for example they are not servlets). One example are JSF managed beans - their methods do not take HttpServletRequest parameters, and so you can obtain the request via the FacesContext, which has them in ThreadLocal variables.

这样做的原因是因为每个请求都由一个单独的线程(由 servlet 容器)处理.所以线程=请求.但是有一个警告——容器倾向于使用线程池.因此,必须始终在 threadlocal 中设置一个新的请求,并且最好在之后对其进行清理(例如在 Filter 中).否则你可能会得到一些意想不到的行为.

The reason this works is because each request is handled by a separate thread (by the servlet container). So thread = request. But there is a caveat - containers tend to use thread pools. So one must always set a fresh request in the threadlocal, and preferably clean it up afterwards (for example in a Filter). Otherwise you can get some unexpected behaviour.

但是你真的应该在你的代码中避免这种情况.如果您需要请求或响应中的任何内容,请将其作为方法参数传递.否则,您可能会违反层边界(例如,如果您想在服务层中使用请求)

But you should really avoid this in your code. If you need anything from the request or response, pass it as method argument around. Otherwise you risk to violate layer boundaries (if you are tempted to use the request in the service layer, for example)

这篇关于ThreadLocal 在 servlet 中存储 ServletRequest 和 Response:有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆