【问题标题】:Best way of sending REST responses in spring boot在 Spring Boot 中发送 REST 响应的最佳方式
【发布时间】:2018-01-11 20:40:56
【问题描述】:

在 Spring Boot 中发送休息响应的最佳方式是什么?另外我应该如何管理发送状态代码才能正确执行?

目前我使用 ResponseEntity 来做,但我怀疑这是最优雅的方式。

示例代码:

@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 类扩展了一个 HashMap 类,只是获取和包装 BindingResult 的错误消息。

【问题讨论】:

    标签: java spring rest controller response


    【解决方案1】:

    我个人认为返回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));
    }
    

    或者,您可以使用status 方法传递HttpStatus 或类似这样的状态代码

    ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ModelErrors(bindingResult));
    ResponseEntity.status(201).body(itemService.addItem(item));
    

    另一种选择是不使用ResponseEntity,只返回您想要的任何类型,但这使您对响应的控制要少得多,并且要求您具有正确的MessageConverter 配置(您可以阅读该配置) here)。

    一个简单的例子可能如下所示

    @RequestMapping("/hotdog")
    public Hotdog hotdog() {
        return new Hotdog("mystery meat", "ketchup, mustard");
    }
    

    如果一切配置正确,您最终会得到这样的响应

    {
        "content": "mystery meat",
        "condiments": "ketchup, mustard"
    }
    

    【讨论】:

    • 甚至不知道我能做到这一点xd。谢谢。所以 ResponseEntity 不是发送响应的坏方法吗?有没有更流行的方法?
    • 我认为ResponseEntity 是要走的路。我已经用另一个选项更新了我的答案。
    猜你喜欢
    • 2020-09-30
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2017-11-04
    • 1970-01-01
    • 2017-11-22
    • 2017-12-05
    相关资源
    最近更新 更多