【问题标题】:RESTful URLs with Jersey 2 subresources?带有 Jersey 2 子资源的 RESTful URL?
【发布时间】:2017-04-20 12:12:29
【问题描述】:

有没有办法将 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();
    }
}

【问题讨论】:

    标签: java rest jersey-2.0


    【解决方案1】:

    您不这样做,而是将CarsResource 的实例注入PersonsResource', and then you call the method ofgetPersonCars`,如下所示

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 2016-11-03
      • 1970-01-01
      相关资源
      最近更新 更多