有 jersey-2 动态构建端点 RESTful 资源。 路径方法
resourceBuilder.path("item/{id}");
定义特定资源的匹配 url 模式。例如。当请求 www.myapp.com/api/item/22 资源时,具有上述路径模式的处理程序将处理请求。
我需要找出请求调用将匹配哪个路径模式(此处为“item/{id}”)。
getMatchedResources() 或 getMatchedURIs() 不提供路径模式列表。
methodBuilder.produces(new MediaType("text", "plain"))
.handledBy(new Inflector<ContainerRequestContext, String>() {
@Override
public String apply(ContainerRequestContext ctx) {
List<Object> resources = ctx.getUriInfo().getMatchedResources();
List<String> uris = ctx.getUriInfo().getMatchedURIs();
return "Programmatically generated endpoint";
}
});
有人解决过类似的问题吗?
最佳答案
我能够通过将请求的上下文转换为 ContainerRequest 然后调用 getMatchedTemplates() 方法来检索匹配的模板。
methodBuilder.produces(new MediaType("text", "plain"))
.handledBy(new Inflector<ContainerRequestContext, String>() {
@Override
public String apply(ContainerRequestContext ctx) {
List<UriTemplate> uriTemplates = ((ContainerRequest) requestContext).getUriInfo().getMatchedTemplates();
if(uriTemplates != null && uriTemplates.size() > 0)
{
UriTemplate uriTemplate = uriTemplates.get(0);
String pathTemplate = uriTemplate.getTemplate();
//pathTemplate == "/item/{id}"
}
return "Programmatically generated endpoint";
}
});
关于java - 如何从请求上下文中获取 url 匹配模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36207816/