javax servlet filter vs jersey filter [duplicate]

空扰寡人 提交于 2021-01-05 23:47:34

问题


I'm planning on writing a servlet application (meant for deployment with OSGI) and use some filters for HTTP header pre-processing. While originally settled on the javax.servlet filter implementation, it occured to me that I actually don't know why/when one would choose to use that vs the Jersey ContainerRequestFilter. Granted the latter comes with some pre-built filters, but arguably so does the former (eg Cors filter). Thus, what should be considered when choosing which API to use? Are there specific cases when one should not be used in favor of the other?


回答1:


Whatever you decide, you will be using a javax.servlet based Filter implementation, since it is the base interface for every Filter you use in Java EE.

http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html

Now, Jersey comes with an implementation that adds some functionality (access to your ContainerRequestContext or whatever you would need inside your Jersey application). Are you using Jersey already in your application? Then go for it, if not I would not bother (at least a priori and without further information) and just go for the most simple possible implementation of javax.servlet.Filter and put it straight into my web.xml




回答2:


The problem with JAX-RS filters is that your are not in control to execute the filter chain

chain.doFilter(request, response);

Because my problem is now to shift a Servlet Filter to a JAX-RS filter but the current Servlet Filter calls the whole filter chain in order to check in the end the response and its status. This is not possible with a JAX-RS filter from my point of view.




回答3:


From https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter12/server_side_filters.html

[...] servlet filters wrap around servlet processing and are run in the same Java call stack. Because JAX-RS has an asynchronous API, JAX-RS filters cannot run in the same Java call stack. Each request filter runs to completion before the JAX-RS method is invoked. [...]

I think, this is a key difference, that should be considered, when choosing the one or the other.



来源:https://stackoverflow.com/questions/24497349/javax-servlet-filter-vs-jersey-filter

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