2011-11-29 60 views
4

我想代码,multileveled像一个REST API:如何使用多级资源编码java jersey REST API?

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

我有一个Java类,它是用@Path(“国家”)

一个国家的资源如何创建一个StateResource .java和CityResource.java,以便我的国家/地区资源可以按照我计划使用的方式使用StateResource?有关如何在Java中构造这种事情的有用链接?

+1

现在你告诉我!我一直在手动创建文件,然后将它们导入到Eclipse中。 –

回答

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以获得来实例化子资源。如果您打算在子资源中使用@PathParam@QueryParam,我相信您需要使用它,因为在通过new自行创建时,运行时不会触及子资源。

+1

您也可以返回CityResource.class以确保运行时管理子资源。 – broadbear