java 在 Spring Boot 中发送 REST 响应的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48215468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way of sending REST responses in spring boot
提问by dudinii
What is the best way to send rest responses in spring boot? Also how should i manage sending status codes to do it properly?
在 Spring Boot 中发送休息响应的最佳方式是什么?另外我应该如何管理发送状态代码以正确执行?
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 的错误消息。
回答by zero01alpha
Personally I think that returning ResponseEntity
is going to be the best choice for a lot of cases. A little more readable way of doing it in my opinion is to use the handy status methods on ResponseEntity
like this
我个人认为,返回将ResponseEntity
是很多情况下的最佳选择。在我看来,这样做的一个小更可读的方式是使用方便的状态方法上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
或者,您可以使用像这样status
传递 aHttpStatus
或状态代码的方法
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"
}