(I\'m not sure exactly how to phrase the title here, and because of that I\'m not really sure how to go about searching for the answer either.)
I have a Java se
There isn't in the servlet API, but you can make your own pretty easily. (Some frameworks like spring-mvc, struts provide such functionality)
Just use a public static ThreadLocal
to store and retrieve the object. You can even store the HttpServletRequest
itself in the threadlocal and use its setAttribute()
/getAttribute()
methods, or you can store a threadlocal Map
, to be agnostic of the servlet API. An important note is that you should clean the threadlocal after the request (with a Filter, for example).
Also note that passing the object as parameter is considered a better practice, because you usually pass it from the web layer to a service layer, which should not be dependent on web-related object, like a HttpContext
.
If you decide that it is fine to store them in a thread-local, rather than passing them around:
public class RequestContext {
private static ThreadLocal
And a necessary filter:
@WebFilter(urlPatterns="/")
public class RequestContextFilter implements Filter {
public void doFilter(..) {
RequestContext.initialize();
try {
chain.doFilter(request, response);
} finally {
RequestContext.cleanup();
}
}
}