【发布时间】: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