2017-04-20 2 views
2

Existe-t-il un moyen d'utiliser Resorces en tant que root et sous-ressource? Je veux appeler mon point final api cette façon:URLs RESTful avec les sous-ressources de Jersey 2?

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

Comment mettre en œuvre mes ressources pour utiliser ce schéma url?

Personne-ressource:

@Path("persons") 
public class PersonsResource { 

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

Voitures ressources:

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

Répondre

0

Vous ne le faites pas de cette façon, au lieu dans PersonsResource', and then you call the method of getPersonCars`, vous injectez une instance de CarsResource comme suit

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