如何从 ContainerRequestContext 获取路径参数

how to get path param from ContainerRequestContext

我想为我的 REST API 端点应用授权过滤器,过滤器需要路径参数来进行过滤。这是我的端点和代码:

端点:

curl --url 'localhost:80/reports/resources/org/12345/product/111 ' --request GET --header 'Authorization: <token here>'

资源码:

@Path("/resources")
public class MyResource extends AbstractResource {
...
    @GET
    @Path("/org/{orgId}/product/{productId}")
    @Produces(MediaType.APPLICATION_JSON)
    @RoleAuthenticated
    public Response getResourcesReport(@PathParam("orgId") String orgId,
                                       @PathParam("productId") String productId,
                                       @Context HttpHeaders headers){....}

过滤器:

@PreMatching
@RoleAuthenticated
public class AuthorizationFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
            MultivaluedMap<String, String> pathparam = requestContext.getUriInfo().getPathParameters();   <--  return empty map  
}

我期待 requestContext.getUriInfo().getPathParameters() returned 地图如下:

orgId 12345
productId 111

怎么会 return 一张空地图?以及如何从 ContainerRequestContext 获取路径参数?

您在过滤器上使用了 @PreMatching 注释。

Javadoc 说:

In case the filter should be applied at the pre-match extension point, i.e. before any request matching has been performed by JAX-RS runtime, the filter MUST be annotated with a @PreMatching annotation.

因此在传入请求被 JAX-RS 运行时匹配到特定资源之前调用过滤器,因此路径参数为空。

所以我猜你需要删除 @PreMatching 注释。