java - 设置和获取 HTTP header 的最佳选项是什么?使用 Apache CXF 拦截器或过滤器

标签 java web-services jax-rs cxf etag

在我的一个项目中,我必须在响应中设置 ETag header ,并读取传入请求中的 if-none-matched header 。截至目前,我已经使用 Apache CXF 过滤器 实现了此功能,但是当我搜索并发现时,也可以使用拦截器 来完成相同的功能。如果我继续使用 CXF 过滤器,我将必须经历哪些显着的优点和/或缺点?

到目前为止,我已经实现了过滤器,并且运行良好,使用过滤器的最佳实践是什么?

最佳答案

这里引用 http://cxf.apache.org/docs/jax-rs-filters.html

Difference between JAXRS filters and CXF interceptors JAXRS runtime flow is mainly implemented by a pair of 'classical' CXF interceptors. JAXRSInInterceptor is currently at Phase.UNMARSHAL (was at Phase.PRE_STREAM before CXF 2.2.2) phase while JAXRSOutInterceptor is currently at Phase.MARSHAL phase.

JAXRS filters can be thought of as additional handlers. JAXRSInInterceptor deals with a chain of Pre and Post Match ContainerRequestFilters, just before the invocation. JAXRSOutInterceptor deals with a chain of ContainerResponseFilters, just after the invocation but before message body writers get their chance.

Sometimes you may want to use CXF interceptors rather than writing JAXRS filters. For example, suppose you combine JAXWS and JAXRS and you need to log only inbound or outbound messages. You can reuse the existing CXF interceptors :

<beans>
<bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
<bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>

<jaxrs:server> 
  <jaxrs:inInterceptors>
    <ref bean="logInbound"/>
  </jaxrs:inInterceptors>
  <jaxrs:outInterceptors>
    <ref bean="logOutbound"/>
  </jaxrs:outInterceptors>
</jaxrs:server>
<jaxws:endpoint>
 <jaxws:inInterceptors>
 <ref bean="logInbound"/>
 </jaxws:inInterceptors>
 <jaxws:outInterceptors>
<ref bean="logOutbound"/>
 </jaxws:outInterceptors>
</jaxws:endpoint>
</beans>

Reusing other CXF interceptors/features such as GZIP handlers can be useful too.

At the moment it is not possible to override a response status code from a CXF interceptor running before JAXRSOutInterceptor, like CustomOutInterceptor above, which will be fixed.

关于java - 设置和获取 HTTP header 的最佳选项是什么?使用 Apache CXF 拦截器或过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39246709/

相关文章:

java - 尝试加载外部库会杀死 JRE

java - 从RestFul的角度来看,使用Jersey(jax-rs)和Servlet有很大的区别吗

web-services - 继续运行 Go Server 作为后台进程

java - 如何从 Apache CXF REST 服务返回 XML 并将其转换为 json?

java - 引导 JAX-RS (RESTEasy)

java - 从大量数据生成大 PDF

java - 为什么引入同级模块会改变 gradle 5 中该模块的依赖规则/顺序?

java - 一个或多个监听器无法启动 SringMVC 电子商务项目

asp.net - javascript 和 ASP.NET AJAX 中的 OO 编程问题

java - 为什么我的 Jersey JAX-RS 服务器抛出一个关于不在 RequestScope 中的 IllegalStateException?