单个资源下的多个GET:REST API

时间:2017-01-22 22:16:19

标签: java rest jax-ws

我试图创建两个彼此链接的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调用都在进行相同的初始和日志记录工作。唯一的区别是方法调用。有没有办法编写相同的代码,只根据路径调用不同的函数?

1 个答案:

答案 0 :(得分:0)

你可以提取一些方法。一个用于ID检查。一个用于记录错误。

public interface IdChecker {
    public void checkId(Long id);
}

public class CustomerWebService extends ... implements IdChecker {

    @Override
    public void checkId(Long id) {
        if (id == null || id == 0)
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("400: customerId cannot be null!").build());
    }

    private void logMessage(Exception e, String reason) {
        log.error(String.format("Exception occurred when %s", reason), e);
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("......").build());
    }

    @GET
    @QueryParam("{customerId}")
    public List<customerModel> getCustomers(@QueryParam("customerId") Long customerId) {
        checkId(customerId);
        try {
           ......
           ......
          return findCustomer(customerId); 
        } catch (Exception e) {
            String action = "fetching the master detail customerId:" + customerId;
            logMessage(e, action);
        }
    }

    @GET
    @Path("{customerId}/moreInfo")
    public List<customerInfoModel> getCustomerInfo(@PathParam("customerId") Long customerId) {
        checkId(customerId);
        try {
          .....
          .....
          return getCustomerInfo(customerId);
        } catch (Exception e) {
            String action = "fetching the customer detail customerId:" + customerId;
            logMessage(e, action);
        }
    }