@Context HttpServletRequest scope in Jersey ContainerResponseFilter

喜你入骨 提交于 2019-12-22 04:33:15

问题


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");
....
}
}

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/18326292/context-httpservletrequest-scope-in-jersey-containerresponsefilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!