2017-08-20 68 views
0

我有一个@Provider应该更换这样的路径变量:替换path参数动态

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

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

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

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

+0

的*电流*的JavaDoc [javax.ws.rs.core.UriInfo.getPathParameters()](https://docs.oracle.com/javaee/7/api/javax/ws/rs/核心/ UriInfo.html#getPathParameters--)说FWIW同样的事情 –

回答

0

我有一个解决方案现在。 这有点麻烦,但它的工作原理。首先,我必须添加一个附加注释@PreMatching。这会导致提供程序在请求中执行得更早,因此您可以在处理该路径之前对其进行处理。缺点是我无法再使用PathParameters,因为占位符{userId}此时未被设置。相反,我不得不由路径段莫名其妙提取的路径信息:

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

不幸的是,我不得不重建从新的整个路径来改变用户ID(包括查询参数!)。

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());