2017-04-20 98 views
2

有沒有辦法使用Resorces作爲根和子資源? 我想打電話給我的API端點這樣:帶Jersey 2子資源的RESTful URL?

GET /persons/{id}/cars  # get all cars for a person 
GET /cars     # get all cars 

如何實現我的資源使用這個網址架構?

人資源:

@Path("persons") 
public class PersonsResource { 

    @GET 
    @Path("{id}/cars") 
    public CarsResource getPersonCars(@PathParam("id") long personId) { 
     return new CarsResource(personId); 
    } 
} 

汽車資源:

@Path("cars") 
public class CarsResource { 

    private Person person; 

    public CarsResource(long personId) { 
     this.person = findPersonById(personId); 
    } 

    @GET 
    public List<Car> getAllCars() { 
     // ... 
    } 

    @GET 
    public List<Cars> getPersonCars() { 
     return this.person.getCars(); 
    } 
} 

回答

0

你不這樣做的,而不是你注入的CarsResource一個實例爲PersonsResource', and then you call the method of getPersonCars`,如下

@Path("persons") 
public class PersonsResource { 

    @inject 
    private CarsResource carsResource; 

    @GET 
    @Path("{id}/cars") 
    public List<Cars> getPersonCars(@PathParam("id") long personId) { 
    return carsResource.getPersonCars(personId); 
    } 
} 


@Path("cars") 
public class CarsResource { 

    @GET 
    @Path("all") 
    public List<Car> getAllCars() { 
    // ... 
    } 


    public List<Cars> getPersonCars(long personId) { 
    Person person = findPersonById(personId); 
    return person.getCars(); 
    } 
}