Jersey 2.4 ReaderInterceptor无法正常工作

时间:2014-01-29 11:41:22

标签: java httprequest jersey-2.0

我正在测试泽西拦截器和过滤器。我有这个Jersey 2.4拦截器代码:

@Provider
@Test
public class TestInterceptor implements WriterInterceptor, ReaderInterceptor {
    private final static Logger log = ....

    @Override
    public void aroundWriteTo (WriterInterceptorContext context) 
        throws IOException, WebApplicationException {
        log.debug("WriterInterceptor");
        context.proceed();
    }

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext ric) 
        throws IOException, WebApplicationException {
        log.debug("ReaderInterceptor");
        return ric.proceed();
    }    
}

我的资源方法:

@Path("{test}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Test
public FooObj test () {
    log.debug("test method");
    return new FooObj();
}

两个过滤器:

@Provider
public class ResponseFil implements ContainerResponseFilter {
    private final static Logger log = ....

    @Override
    public void filter(ContainerRequestContext crc, ContainerResponseContext crc1)
        throws IOException {
        log.debug("ResponseFil");
    }
}

@Provider
public class RequestFil implements ContainerRequestFilter {
    private final static Logger log = ....
    @Override
    public void filter(ContainerRequestContext crc) throws IOException {
        log.debug("RequestFil");
    }
}

和我的web.xml servlet配置:

<servlet>
    <description>Servlet test</description>
    <servlet-name>REST_servlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.test.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

当我从firefox输入url地址资源并获得结果时,日志控制台会显示:

RequestFil
test method
ResponseFil
WriterInterceptor

为什么不执行ReaderInterceptor?我试图用两个自定义绑定名称(@Test和@ Test2)将写入和读取器拦截器分成两个类,结果相同。

由于

1 个答案:

答案 0 :(得分:7)

仅当请求/响应实体可用时才执行拦截器(ReaderInterceptor / WriterInterceptor的实现)。在您的情况下,这意味着只有WriterInterceptor正在执行,因为您正在从资源方法向客户端发送实体(FooObj的实例)。如果您使用POST方法接收用户的输入,则也会调用ReaderInterceptor

如果您需要修改请求,即使没有实体,也请使用ContainerRequestFilter / ContainerResponseFilter

有关详细信息,请参阅JAX-RS 2.0规范。