我正在尝试使用 dropwizard 实现 RequestDispatcher,它应该查看帖子正文中的实体并计算某些统计数据。
所以,我实现了一个 ResourceMethodDispatchAdapter
和 ResourceMethodDispatchProvider
,我能够成功地注入(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/