【问题标题】:Correct response of RESTfull web serviceRESTful Web 服务的正确响应
【发布时间】:2017-05-26 15:24:22
【问题描述】:

在 GET、POST、PUT、DELETE 请求之后我应该返回什么(JSON 格式)?

我看到了几个变种。例如: 1) 获取:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET,
        headers = "Accept=application/json")
public Shop getShopById(@PathVariable long id) {
    return mainService.getShopById(id);
}

2) 获取:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET,
        headers = "Accept=application/json")
public ResponseEntity<Shop> getShopById(@PathVariable long id) {
    Shop shop = mainService.getShopById(id);

    if (shop == null) {
        return new ResponseEntity<Shop>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Shop>(shop, HttpStatus.OK);
}

1) 发布:

@RequestMapping(value="/users", method = RequestMethod.POST)
public User addShop(@RequestBody User user) {
    mainService.addShop(user);
    return user;enter code here
}

2) 发布:

@RequestMapping(value="/users", method = RequestMethod.POST)
public User addShop(@RequestBody User user) {
    mainService.addShop(user);

    HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/users").buildAndExpand(user.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

那么返回响应的正确方法是什么?它应该只是作为 User 或 ResponseEntity 的对象吗?关于 PUT 和 DELETE 方法的相同问题。

【问题讨论】:

    标签: json rest spring-mvc


    【解决方案1】:

    您可能想看看HATEOAS

    【讨论】:

      【解决方案2】:

      据我所知,这取决于您要返回的 HttpStatus(响应代码)。我总是返回 ResponseEntity≤?> 因为它允许指定 HttpStatus,这对 REST 很重要。

      (您还应该指定 @ResponseBody 并生成 = MediaType.APPLICATION_JSON_VALUE)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-15
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 2014-01-12
        • 2010-09-07
        相关资源
        最近更新 更多