REST子资源定位器



我正在通读RESTful Java with JAX-RS 2.0,2nd Edition这本书,我很难理解子资源定位器是如何工作的,下面是所提供示例的精简版。

客户数据库资源类

@Path("/customers")
public class CustomerDatabaseResource {
   @Path("{database}-db")
   public CustomerResource getDatabase(@PathParam("database") String db) {
      // find the instance based on the db parameter
      CustomerResource resource = locateCustomerResource(db);
      return resource;
   }
   protected CustomerResource locateCustomerResource(String db) {
     ...
   }
}

客户资源类

public class CustomerResource {
   private Map<Integer, Customer> customerDB =
                          new ConcurrentHashMap<Integer, Customer>();
   private AtomicInteger idCounter = new AtomicInteger();
   public CustomerResource(Map<Integer, Customer> customerDB)
   {
      this.customerDB = customerDB;
   }
   @GET
   @Path("{id}")
   @Produces("application/xml")
   public StreamingOutput getCustomer(@PathParam("id") int id) {
     ...
   }

因此,我理解,当GET /customers/northamerica-db/333这样的请求传入时,将首先匹配方法CustomerDatabaseResource.getDatabase()上的表达式,该表达式将根据位置创建CustomerResource的正确实例。

我不明白的是接下来会发生什么。。。

  1. 实例resource被返回,但返回到哪里?

  2. web服务如何知道然后使用方法CustomerResource.getCustomer()来匹配和处理请求的剩余部分?我想这是因为CustomerDataBaseResource类没有@GET,但我并不真正理解转换是如何发生的。

  3. 这是RESTEasy特有的吗?

  1. 实例资源被返回,但返回到哪里

它的get返回到请求处理引擎,并继续寻找匹配的方法(在返回资源对象内),就像任何其他请求一样。

  1. web服务如何知道然后使用方法CustomerResource.getCustomer()来匹配和处理请求的剩余部分?我想这是因为CustomerDataBaseResource类没有@GET,但我真的不明白转换是如何发生的

资源定位器不应该用Http方法进行注释。这就是它们被称为定位器的原因。由于它不是要调用的资源方法,因此不应对其进行注释。想象一下这个

public class CustomerResource {
    @PUT
    @Path("{id}")
    public Response updateCustomer(Customer customer) {}
    @POST
    @Path("{id}")
    public Response createCustomer(Customer customer) {}
}

如果CustomerDataBaseResource.getDatabase()要用Http方法进行注释,那么我们就无法使用上面的方法。定位器所需要的只是@Path,URI匹配将从该路径开始继续。

/customers/database-us

一旦创建了CustomerResource,如果请求uri是/customers/database-us/123,那么现在的下一个逻辑步骤是基于uri找到匹配的资源方法,因此将寻找用@Path注释的与123匹配的东西。然后检查Http方法。

  1. 这是RESTEasy特有的吗

通过jax-rs规范,我没有看到任何关于子资源定位器的内容,但Jersey也实现了这种确切的行为。我读过你提到的那本书,据我所知,作者并没有真正深入了解任何特定于实现的东西,但确实提到了大多数实现者实现的常见特性,这不是规范的一部分。也许这就是其中之一。


更新

因此在规范中。转到链接并下载规范。您将在3.4.1 Sub Resources下找到所有内容,并在3.7.2 Request Matching 中找到一些请求匹配的算法信息

最新更新