[英]Best way of sending REST responses in spring boot
What is the best way to send rest responses in spring boot? 在春季启动时发送休息响应的最佳方法是什么? Also how should i manage sending status codes to do it properly?
另外我应该如何管理发送状态代码才能正确完成?
Currently i do it using ResponseEntity but i doubt this is the most elegant way. 目前我使用ResponseEntity,但我怀疑这是最优雅的方式。
Sample code: 示例代码:
@PostMapping()
public ResponseEntity post(@Valid @RequestBody Item item, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return new ResponseEntity<>(new ModelErrors(bindingResult), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(itemService.addItem(item), HttpStatus.CREATED);
}
ModelErrors class extends a HashMap class and just fetches and wraps the BindingResult's error messages. ModelErrors类扩展了HashMap类,只是获取并包装BindingResult的错误消息。
Personally I think that returning ResponseEntity
is going to be the best choice for a lot of cases. 就个人而言,我认为返回
ResponseEntity
将是许多案例的最佳选择。 A little more readable way of doing it in my opinion is to use the handy status methods on ResponseEntity
like this 在我看来,更可读的方法就是在
ResponseEntity
上使用方便的状态方法
@PostMapping()
public ResponseEntity post(@Valid @RequestBody Item item, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return ResponseEntity.badRequest().body(new ModelErrors(bindingResult));
}
return ResponseEntity.created().body(itemService.addItem(item));
}
Alternatively, you can use the status
method passing a HttpStatus
or status code like this 或者,您可以使用传递
HttpStatus
或状态代码的status
方法
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ModelErrors(bindingResult));
ResponseEntity.status(201).body(itemService.addItem(item));
Another option is to just return whatever type you'd like without using ResponseEntity
, but this gives you a lot less control over the response and requires that you have the proper MessageConverter
configuration (you can read up on that here ). 另一种选择是在不使用
ResponseEntity
情况下返回您想要的任何类型,但是这使您对响应的控制更少,并且要求您具有正确的MessageConverter
配置(您可以在此处阅读)。
A simple example might look like this 一个简单的例子可能看起来像这样
@RequestMapping("/hotdog")
public Hotdog hotdog() {
return new Hotdog("mystery meat", "ketchup, mustard");
}
and if everything is configured correctly you'd end up with a response like this 如果一切都配置正确,你最终会得到这样的回应
{
"content": "mystery meat",
"condiments": "ketchup, mustard"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.