jersey requestdispatcher 执行顺序

jersey requestdispatcher execution order

我正在尝试使用 dropwizard 实现 RequestDispatcher,它应该查看帖子正文中的实体并计算某些统计数据。

所以,我实现了 ResourceMethodDispatchAdapterResourceMethodDispatchProvider,我能够成功注入和调用我的 RequestDispatcher,

 private static class InspectRequestDispatcher implements RequestDispatcher {

    private final RequestDispatcher dispatcher;

    private InspectRequestDispatcher(RequestDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    public void dispatch(final Object resource, final HttpContext context) {
        final Saying day = context.getRequest().getEntity(Saying.class);
        dispatcher.dispatch(resource, context); // this throws ConstraintViolationException
    }
}

上面的代码抛出异常,因为我已经读取了正文(这是可以理解的),我可以重置流,但是我将支付两次读取正文的惩罚。

是否可以在注入参数后拦截方法调用?以某种方式将此拦截器安排为最后一个?

使用 dropwizard 7 版本

如果您要使用 ContainerRequestFilter instead of a RequestDispatcher, you could make use of the CachedEntityContainerRequest 就是为了这个目的。

A cached entity in-bound HTTP request that caches the entity instance obtained from the adapted container request.

A filter may utilize this class if it requires an entity of a specific type and that same type will also be utilized by a resource method.

你基本上会这样使用它:

@Provider
public class StatsFilter implements ContainerRequestFilter {
    @Override
    public ContainerRequest filter(ContainerRequest request) {
        final CachedEntityContainerRequest cachedRequest
                = new CachedEntityContainerRequest(request);

        final Saying saying = cachedRequest.getEntity(Saying.class);

        return cachedRequest;
    }
}

然后注册过滤器。