如何从ContainerRequestContext获取路径参数

use*_*587 6 java jax-rs jersey

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

终点:

curl --url 'localhost:80/reports/resources/org/12345/product/111 ' --request GET --header 'Authorization: <token here>'
Run Code Online (Sandbox Code Playgroud)

资源代码:

@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){....}
Run Code Online (Sandbox Code Playgroud)

过滤:

@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  
}
Run Code Online (Sandbox Code Playgroud)

我期待requestContext.getUriInfo().getPathParameters()返回以下地图:

orgId 12345
productId 111
Run Code Online (Sandbox Code Playgroud)

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

wer*_*ero 7

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

Javadoc说:

如果应该在匹配前扩展点应用过滤器,即在JAX-RS运行时执行任何请求匹配之前,必须使用@PreMatching注释对过滤器进行注释.

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

所以我想你需要删除@PreMatching注释.