【发布时间】:2017-01-22 22:16:19
【问题描述】:
我正在尝试创建两个相互链接的 GET 请求,也就是说,一个是另一个的孩子。请看下面的代码:
@GET
@QueryParam("{customerId}")
public List<customerModel> getCustomers(@QueryParam("customerId") Long customerId) {
if (customerId== null || customerId== 0)
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("400: customerId cannot be null!").build());
try {
......
......
return findCustomer(customerId);
} catch (Exception e) {
log.error("Exception occurred when fetching the master detail customerId:" + customerId+", error :"+e.getMessage(), e);
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("......").build());
}
}
@GET
@Path("{customerId}/moreInfo")
public List<customerInfoModel> getCustomerInfo(@PathParam("customerId") Long customerId) {
if (customerId== null || customerId== 0)
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("customerId cannot be null").build());
try {
.....
.....
return getCustomerInfo(customerId);
} catch (Exception e) {
log.error("Exception occurred when fetching the customer detail customerId:" + e.getMessage(), e);
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("....").build());
}
}
如果我们注意到,两个 GET 调用都在执行相同的初始和日志记录工作。唯一的区别是方法调用。有没有办法编写相同的代码,只根据路径调用不同的函数?
【问题讨论】:
-
你为什么不创建另一个 pathparam /{moreinfo} 并检查这个参数是否存在?
-
您使用的框架是什么?
-
@CamilleGerin-Roze,我们可以这样做吗?你能提供一个简单的例子来说明我们如何做到这一点吗?
-
据我所知,除了
findCustomer(customerId);和getCustomerInfo(customerId);之外,您的方法完全相同,但两种方法都返回List<customerModel>,所以这很混乱。 -
@cricket_007 抱歉打错了,他们定义返回不同的模型