簡體   English   中英

包含Jersey 2子資源的RESTful URL?

[英]RESTful URLs with Jersey 2 subresources?

有沒有辦法同時使用Resorces作為根資源和子資源? 我想通過以下方式調用我的api端點:

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

如何實現我的資源以使用此url模式?

人員資源:

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

您沒有那樣做,而是將一個CarsResource實例注入PersonsResource', and then you call the method of getPersonCars` PersonsResource', and then you call the method of ,如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM