ThreadLocal to store ServletRequest and Response in servlet: what for?

后端 未结 8 734
情歌与酒
情歌与酒 2020-12-05 21:19

Once I have came across a pattern, where ServletRequest and response objects are put to servlet\'s local ThreadLocal variables. The servlet class h

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 21:35

    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.

    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)

提交回复
热议问题