【问题标题】:Jersey getting template pathJersey 获取模板路径
【发布时间】:2014-12-12 04:34:00
【问题描述】:

我正在使用 Jersey 2,我想获取 URI 模板。 原因是我创建了一个基于 URI 进行验证的身份验证系统。我设法工作了:

    @Override
    public void filter(ContainerRequestContext containerRequest) throws IOException {

        String method = containerRequest.getMethod();
        String uri = containerRequest.getUriInfo().getPath();
    }

问题是 getPath 返回类似:

/companies/1

我希望它返回

/companies/{id}

我是这样声明的:

@Path("{id}")

谢谢

编辑我以为我在这里找到了它:

@Context
private ExtendedUriInfo uriInfo;

//...
Resource matchedModelResource = uriInfo.getMatchedModelResource();
System.out.println(matchedModelResource.getPathPattern().getTemplate().getTemplate());

但你猜怎么着? matchedModelResource 为空。

还有,这个:

List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();

返回一个空的 UriTemplate 列表。 :( 为什么没有设置数据?

【问题讨论】:

    标签: java filter jersey uri


    【解决方案1】:

    好的。所以答案是使用:

     uriInfo.getMatchedTemplates();
    

    uriInfo 实际上是 ExtendedUriInfo

    这是我为获得正确语法而编写的代码:

        List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();
    
        StringBuilder builder = new StringBuilder();
    
        for (int i = matchedTemplates.size() - 1; i >= 0; i--) {
            builder.append(matchedTemplates.get(i).getTemplate().substring(1));
        }
    
        System.out.println("Permission is: " + builder.toString());
       // Prints:
       // Permission is: sig/companies/{id}
    

    数据之前为空或为空的原因是因为我的过滤器类中有一个@PreMatching 注释。请不要问为什么。

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 2023-04-02
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多