【问题标题】:JAX-RS filters calling sequenceJAX-RS 过滤器调用序列
【发布时间】:2015-03-20 06:25:48
【问题描述】:

我对 JAX-RS 过滤器的实现如下,

请求过滤器是:

   public class AuthorizationRequestFilter implements ContainerRequestFilter {
        public static long entryTime;
         @Override
            public void filter(ContainerRequestContext requestContext)
                            throws IOException {

             /*some preprocessing before unmarshalling*/
            }
    }

响应过滤器是:-

公共类 ResponseFilter 实现 ContainerResponseFilter {

 @Override
        public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {

        if (!requestContext.getMethod().equalsIgnoreCase("Head")) {
             /*Some processing after Marshalling*/

        }

}

我的处理程序是:-

@POST
@Path("abc")
@Produces(MediaType.APPLICATION_XML)
public  Response createABC(App app){
/*lines of code*/
return Response.status(Status.CRETED).entity(abc).build();
}

我的问题是在 Marshallling 和 Unmarshalling 之后调用的过滤器,即在方法 AuthorizationRequestFilter 和 abc 之后创建的应用程序对象在调用响应过滤器之前被编组

【问题讨论】:

    标签: jaxb jax-rs marshalling unmarshalling


    【解决方案1】:

    在解组之前调用请求过滤器。这应该很明显,因为您仍然可以访问实体输入流(这意味着它尚未被读取)。您可以通过编写一个简单的MessageBodyReader 来轻松测试这一点。在请求过滤器中设置一个任意的header,然后你就可以从阅读器readFrom方法中提取相同的header。

    响应过滤器将在编组之前调用。同样,这可以很容易地通过编写一个简单的MessageBodyWriter 来测试。在过滤器中设置任意标题,您应该可以在作者的writeTo 方法中访问它。

    如果你想在编组之后执行一些操作,你可以使用WriterInterceptor,它包装了调用作者的编组方法。例如

    @Provider
    public class SimpleIntercetor implements WriterInterceptor{
    
        @Override
        public void aroundWriteTo(WriterInterceptorContext context) 
                throws IOException, WebApplicationException {
    
            // Processing before marshalling
    
            context.proceed();  // marshal
    
            // Processing after marshalling
        }
    }
    

    一些资源:

    这些链接指向 Jersey 文档,但拦截器、读取器、编写器是 JAX-RS 2.0 的标准,因此该文档应该适用于您正在使用的任何实现(大部分 :-)

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 2016-07-23
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多