问题描述
一旦我遇到一个模式,其中 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?
推荐答案
重点是让类中的请求和响应对象不会有它们(例如它们不是小服务程序)。一个例子是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容器)。所以thread = request。但有一点需要注意 - 容器倾向于使用线程池。因此,必须始终在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:对于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!