2017-04-20 3 views
2

Gibt es eine Möglichkeit, Resorces sowohl als root als auch als Unterressource zu verwenden? Ich mag meinen api Endpunkt so nennen:REST-konforme URLs mit Jersey 2-Unterressourcen?

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

Wie meine Ressourcen implementieren dieses URL-Schema zu benutzen?

Person Ressource:

@Path("persons") 
public class PersonsResource { 

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

Autos Ressource:

@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(); 
    } 
} 

Antwort

0

Sie tun es nicht, dass die Art und Weise, Sie stattdessen eine Instanz von CarsResource in PersonsResource', and then you call the method of getPersonCars` injizieren, wie

folgt
@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(); 
    } 
}