如何在返回String的Spring MVC @ResponseBody方法中响应

如何在返回String的Spring MVC @ResponseBody方法中响应HTTP 400错误?

我正在使用Spring MVC作为一个简单的JSON API,@ResponseBody基于以下方法。(我已经有一个直接生成JSON的服务层。)

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")@ResponseBodypublic String match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        // TODO: how to respond with e.g. 400 "bad request"?
    }
    return json;}

问题是,在给定的场景中,用HTTP 400错误响应的最简单,最干净的方法是什么?

我确实遇到过这样的方法:

return new ResponseEntity(HttpStatus.BAD_REQUEST);

...但我不能在这里使用它,因为我的方法的返回类型是String,而不是ResponseEntity。


FFIVE
浏览 1152回答 3
3回答

墨色风雨

将您的退货类型更改为ResponseEntity<>,然后您可以使用以下400return&nbsp;new&nbsp;ResponseEntity<>(HttpStatus.BAD_REQUEST);并提出正确的要求return&nbsp;new&nbsp;ResponseEntity<>(json,HttpStatus.OK);更新1在4.1之后,ResponseEntity中有辅助方法可以用作return&nbsp;ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);和return&nbsp;ResponseEntity.ok(json);
打开App,查看更多内容
随时随地看视频慕课网APP