【问题标题】:Replace path parameter dynamically动态替换路径参数
【发布时间】:2017-08-20 16:11:55
【问题描述】:

我有一个 @Provider 应该像这样替换一个路径变量:

@Provider
@Priority(value = 1)
public class SecurityCheckRequestFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        //CODE

        requestContext.getUriInfo().getPathParameters().putSingle("userId", someNewUserId);
    }
}

当我调试它时,路径变量“userId”似乎被替换了,但在工作流后期的端点(例如/user/{userId}),旧值再次出现。什么都没有被替换。在最新的 RestEasy 文档中没有关于此行为的信息,但在 very old Resteasy doc 中,有一个信息,getPathParameters() 返回一个不可修改的列表。如果它是不可修改的,为什么我可以替换提供者中的值呢? 然而,该值不会被替换。如何用新值覆盖现有路径参数?

(当然,我可以将新的 userId 添加为一些标头参数并稍后在端点中获取信息,但这不是一个好的解决方案)

【问题讨论】:

标签: jakarta-ee jax-ws resteasy


【解决方案1】:

我现在有一个解决方案。 这有点麻烦,但它确实有效。首先,我必须添加一个额外的注解@PreMatching。这会导致提供程序在请求中更早地执行,因此您可以在处理路径之前对其进行操作。缺点是我不能再使用PathParameters,因为此时没有设置占位符{userId}。相反,我不得不以某种方式通过路径段从路径中提取信息:

List<PathSegment> pathSegments = requestContext.getUriInfo().getPathSegments();

不幸的是,我不得不从新的(包括查询参数!)重建整个路径以更改 userId。

String fullPath = requestContext.getUriInfo().getPath();
MultivaluedMap<String, String> queryParameters = requestContext.getUriInfo().getQueryParameters(true);

String modifiedPath = fullPath.replaceFirst(obfuscationId, userId); 

UriBuilder uriBuilder = UriBuilder.fromPath(modifiedPath);
queryParameters.forEach((k,v) -> { uriBuilder.queryParam(k, v.get(0)); } );
requestContext.setRequestUri(uriBuilder.build());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多