泽西岛:获取方法的URL

时间:2017-05-05 07:46:07

标签: 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方法的网址,例如此/v0/app/100

更新:

我想从getApp

以外的方法获取网址

1 个答案:

答案 0 :(得分:3)

如果您使用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());
    }
}