gpt4 book ai didi

java - 如何从我的 Dropwizard 资源中访问已包装在自定义类中的请求?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:27:38 25 4
gpt4 key购买 nike

我正在使用 Dropwizard,我想从过滤器中包装一个请求对象,并从我的资源类中获取对该实例的访问权限

例如执行以下操作

过滤器.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);
}
}
...

资源.java

@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public class DemoResource {

@GET
@Timed
public Response get(@Context UriInfo uriInfo, @Context RequestWrapper request) {

...

这不起作用,我也没有任何理由期望它起作用,但这似乎是解释我正在尝试做的事情的好方法。

最佳答案

试试这里记录的这个 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;
}
}
}

只需在您的应用程序 run() 中添加:

environment.jersey().getResourceConfig().getContainerRequestFilters().add(new DateNotSpecifiedFilter());

关于java - 如何从我的 Dropwizard 资源中访问已包装在自定义类中的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19382343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com