I am writing an Jersey Response filter. I am using Jersey 1.17. I want to get access to some attributes of the httpServletRequest in the filter API. The way what i am doing right now is as below. Is it safe to inject the servletRequest like in the snippet below or will this cause some kind of concurrency issues? If there are multiple requests coming in conncurrently, will the servletRequest in different requests overwrite each other? Thanks for your hlep.
public class LoggingFilter implements ContainerResponseFilter {
@Context private HttpServletRequest servletRequest;
@Override
public ContainerResponse filter(final ContainerRequest req, final ContainerResponse resp) {
String s = this.servletRequest.getAttribute("xxx");
....
}
}
Section 9.1 (latest, 5.1 previously) Concurrency of the JAX-RS specification states:
Context is specific to a particular request but instances of certain JAX-RS components (providers and resource classes with a lifecycle other than per-request) may need to support multiple concurrent requests. When injecting an instance of one of the types listed in Section 9.2, the instance supplied MUST be capable of selecting the correct context for a particular request. Use of a thread-local proxy is a common way to achieve this.
So, as per the specification, JAX-RS implementations (e.g. Jersey) are required to ensure that the context is safe. Keep doing what you're doing.
See also: Extract request attributes from container request of Jersey
You're safe. When you're injecting HttpServletRequest
/ HttpServletResponse
you're not dealing with a particular instance but rather with a proxy through which you're invoking calls on a real instance stored in a ThreadLocal object. Each request is processed by a separate thread which has access to it's own HttpServletRequest
/ HttpServletResponse
. Beside injecting HttpServletRequest
/ HttpServletResponse
you can also inject ThreadLocal<HttpServletRequest>
/ ThreadLocal<HttpServletResponse>
and through '#get()` method you can obtain the real request / response instances intead of proxies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With