我正在使用Dropwizard,我想从过滤器中包装一个请求对象,并从我的资源类中获取对该实例的访问权
e.g。执行以下操作
Filter.java
public class ServiceRequestExtractionFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
ProxyResourceRequest requestWrapper = new RequestWrapper(httpRequest, svcRequestData);
chain.doFilter(requestWrapper, response);
}
}
...
Resource.java
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public class DemoResource {
@GET
@Timed
public Response get(@Context UriInfo uriInfo, @Context RequestWrapper request) {
...
这不起作用,也没有任何理由期望它,但它似乎是解释我想要做的事情的好方法。
答案 0 :(得分:2)
请尝试此处记录的此ContainerFilter:http://dropwizard.io/manual/core.html#jersey-filters
public class DateNotSpecifiedFilter implements ContainerRequestFilter {
@Context ExtendedUriInfo extendedUriInfo;
@Override
public ContainerRequest filter(ContainerRequest request) {
boolean methodNeedsDateHeader = extendedUriInfo.getMatchedMethod().isAnnotationPresent(DateRequired.class);
String dateHeader = request.getHeaderValue(HttpHeaders.DATE);
if (methodNeedsDateHeader && dateHeader == null) {
Exception cause = new IllegalArgumentException("Date Header was not specified");
throw new WebApplicationException(cause, Response.Status.BAD_REQUEST);
} else {
return request;
}
}
}
只需在应用程序运行()中添加它:
environment.jersey().getResourceConfig().getContainerRequestFilters().add(new DateNotSpecifiedFilter());