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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…