如何使用多级资源编写java jersey REST API代码?

时间:2011-11-29 21:48:43

标签: java rest jax-rs

我想编写一个多层次的REST API,如:

/country
/country/state/
/country/state/{Virginia}
/country/state/Virginia/city
/country/state/Virginia/city/Richmond

我有一个java类,它是具有@Path(“country”)

的Country资源

如何创建StateResource.java和CityResource.java,以便我的Countryresource可以按照我计划使用的方式使用StateResource?关于如何在Java中构造此类事物的任何有用链接?

1 个答案:

答案 0 :(得分:19)

CountryResource类需要使用@Path注释到子资源CityResource的方法。默认情况下,您负责创建CityResource例如

的实例
@Path("country/state/{stateName}")
class CountryResouce {

    @PathParam("stateName")
    private String stateName;

    @Path("city/{cityName}")
    public CityResource city(@PathParam("cityName") String cityName) {
        State state = getStateByName(stateName);

        City city = state.getCityByName(cityName);

        return new CityResource(city);
    }

}

class CityResource {

    private City city;

    public CityResource(City city) {
        this.city = city;
    }

    @GET
    public Response get() {
        // Replace with whatever you would normally do to represent this resource
        // using the City object as needed
        return Response.ok().build();
    }
}

CityResource提供了处理HTTP谓词的方法(在这种情况下为GET)。

您应该查看有关子资源定位符的Jersey documentation以获取更多信息。

另请注意,Jersey提供ResourceContext来获取 it 来实例化子资源。如果您要在子资源中使用@PathParam@QueryParam,我认为您需要使用此资源,因为运行时不会通过new自行创建子资源。

相关问题