java - jersey requestdispatcher 执行顺序

标签 java jersey jetty dropwizard

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

所以,我实现了一个 ResourceMethodDispatchAdapterResourceMethodDispatchProvider,我能够成功地注入(inject)和调用我的 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
    }
}

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

是否可以在注入(inject)参数后拦截方法调用?以某种方式安排这个拦截器成为最后一个拦截器?

使用 dropwizard 7 版本

最佳答案

如果您要使用 ContainerRequestFilter您可以使用 CachedEntityContainerRequest 而不是 RequestDispatcher这就是这个意思。

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;
    }
}

然后只需注册过滤器即可。

关于java - jersey requestdispatcher 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40160040/

相关文章:

Java正则表达式,奇怪的错误

java - Jsoup:从一段javascript中解析html

java - JerseyTest 字段在资源中变为 NULL

java - Swagger 生成的 JAX-RS 服务器与 ElasticSearch 依赖关系中断

java - 获取http get后,我应该以什么格式从django响应到android?

java - block 池 <registering> 初始化失败(Datanode Uuid 未分配)

Java (Jersey 2 + Grizzly 2) JAX-RS 端点的自定义资源注释?

java - 在 neo4j 服务器扩展中使用 JSON

java - maven jetty 错误 'Config error at <Set name="线程池">'

scala - sbt、 jetty 和类路径