在GET,POST,PUT,DELETE请求之后我应该返回什么(JSON格式)?
我看到了几个变种。例如: 1)GET:
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET,
headers = "Accept=application/json")
public Shop getShopById(@PathVariable long id) {
return mainService.getShopById(id);
}
2)GET:
@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)POST:
@RequestMapping(value="/users", method = RequestMethod.POST)
public User addShop(@RequestBody User user) {
mainService.addShop(user);
return user;enter code here
}
2)POST:
@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方法的相同问题。
答案 0 :(得分:0)
您可能需要查看HATEOAS。
答案 1 :(得分:0)
据我所知,这取决于你想要返回的HttpStatus(响应代码)。我总是返回ResponseEntity≤?&gt;因为它允许指定HttpStatus,这对REST很重要。
(您还应该指定@ResponseBody并生成= MediaType.APPLICATION_JSON_VALUE)