java - Jersey:获取方法的 URL

标签 java jersey uri builder

我想获取特定方法的 URI 而无需对其进行“硬编码”。

我尝试了 UriBuilder.fromMethod 但它只生成在该方法的 @Path 注释中指定的 URI,它没有考虑 @Path 它所在的资源类。

例如,这是类

@Path("/v0/app")
public class AppController {

    @Path("/{app-id}")
    public String getApp(@PathParam("app-id") int appid) {
        // ...
    }

}

我想获取 getApp 方法的 URL,例如这个 /v0/app/100

更新:

我想从 getApp 以外的方法获取 URL

最佳答案

如果您使用 UriBuilder.fromResource,它会起作用,然后使用 path(Class resource, String method) 添加方法路径

URI uri = UriBuilder
        .fromResource(AppController.class)
        .path(AppController.class, "getApp")
        .resolveTemplate("app-id", 1)
        .build();

不确定为什么它不适用于 fromMethod

这是一个测试用例

public class UriBuilderTest {

    @Path("/v0/app")
    public static class AppController {

        @Path("/{app-id}")
        public String getApp(@PathParam("app-id") int appid) {
            return null;
        }
    }

    @Test
    public void testit() {
       URI uri = UriBuilder
               .fromResource(AppController.class)
               .path(AppController.class, "getApp")
               .resolveTemplate("app-id", 1)
               .build();

        assertEquals("/v0/app/1", uri.toASCIIString());
    }
}

关于java - Jersey:获取方法的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799297/

相关文章:

java - 如何从 Firebase 获取数组列表对象

java - 简单的 XML 框架 - 奇怪的错误

c# - CreateStreamedFileFromUriAsync : How can i pass a IRandomAccessStreamReference?

java - 非法参数异常 : URI is not hierarchical when calling existing folder

java - 索引 103 处格式错误的转义对 : http://localhost:8025/oauth2db/oauth/token? grant_type=password&username=nithi5@gmail.com&password=nithi%"

java - 将 Struts 1 迁移到 Struts 2

java - 避免数组中出现重复的条目

java - 带 Jersey 的 JAX-RS 无法在 JBoss AS 中工作

web-services - Jersey 客户端异常 : A message body writer was not found

ruby-on-rails - Ruby 的错误 URI