我想编写一个多层次的REST API,如:
/country
/country/state/
/country/state/{Virginia}
/country/state/Virginia/city
/country/state/Virginia/city/Richmond
Run Code Online (Sandbox Code Playgroud)
我有一个java类,它是一个带有@Path("country")的Country资源
如何创建StateResource.java和CityResource.java,以便我的Countryresource可以按照我计划使用它的方式使用StateResource?有关如何在Java中构造此类事物的任何有用链接?
Dou*_*rop 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();
}
}
Run Code Online (Sandbox Code Playgroud)
CityResource提供处理HTTP谓词的方法(GET在本例中).
您应该查看有关子资源定位器的Jersey 文档以获取更多信息.
另请注意,Jersey提供了一个ResourceContext来使其实例化子资源.如果你打算使用@PathParam或者@QueryParam在子资源中我认为你需要使用它,因为运行时不会触及子资源new.
| 归档时间: |
|
| 查看次数: |
7627 次 |
| 最近记录: |