2011-11-29 44 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