一个请求下的多个资源:RESTful API设计模式

时间:2017-01-20 21:02:32

标签: java rest jax-rs wildfly-8

我正在尝试创建一个GET请求,我有两个不同的请求。由于两种资源都是相互关联的,我试图把它们放在一个“子资源”之下。 第一个是:

  @QueryParam("{customerId}")
  public List<customerModel> getCustomer(@QueryParam("customerId") Long customerId) {....}

这取决于customerId

获取客户的名字
@QueryParam("{customerId}/details")
public List<customerDetailModel> getCustomerDetail(@QueryParam("customerId") Long customerId) {....}

这将获取客户的详细信息(电话号码,地址等)

我正在使用以下内容运行第一个(正常): ......?客户ID = 7453112

但是当我点击以下网址时,我无法达到第二个请求: ......?客户ID = 7453112 /细节

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

您需要使用@RequestMapping

像: @RequestMapping("/{customerId}")@RequestMapping("/{customerId}/details")

您的网址变为7453112/details而不是查询参数。

答案 1 :(得分:0)

您可以在/details注释中指定@Path,然后使用相同的查询参数,如下所示:

@Path("/details/{customerId}")
public List<customerDetailModel> getCustomerDetail(@PathParam("customerId") Long customerId) {....}

然后您的网址将如下所示:

.../details/7453112

或者,如果您想继续将其用作查询参数,您可以执行以下操作:

@Path("/details")
public List<customerDetailModel> getCustomerDetail(@QueryParam("customerId") Long customerId) {....}

使用此网址:

.../details?customerId=xxx

答案 2 :(得分:0)

资源方法必须使用@Path和请求方法指示符(例如@GET@POST@PUT进行注释, @DELETE@HEAD@OPTIONS。您的@QueryParam注释放错了地方。

顺便说一下,对于这种情况,您应该考虑使用路径参数而不是查询参数。因此,您应该在方法参数中使用@PathParam而不是@QueryParam。有关何时使用查询或路径参数的更多详细信息,请查看此answer

另外,如果您通过其唯一标识符请求资源,也不确定为什么要返回List。在这种情况下,您应该返回单个资源的表示(而不是多个资源的表示)。

所以你的资源类如下:

@Path("customers")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class CustomerResource {

    @GET
    @Path("{customerId}")
    public CustomerModel getCustomer(@PathParam("customerId") Long id) {
        ...
    }

    @GET
    @Path("{customerId}/details")
    public CustomerDetailModel getCustomerDetail(@PathParam("customerId") Long id) {
        ...
    }
}

可以按如下方式请求第一个端点:

GET http://example.com/api/customers/1

可以按如下方式请求第二个端点:

GET http://example.com/api/customers/1/details
相关问题