如何在返回字符串的 Spring MVC @ResponseBody 方法中响应 HTTP 400 错误? [英] How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
问题描述
我将 Spring MVC 用于简单的 JSON API,使用基于 @ResponseBody
的方法,如下所示.(我已经有一个直接生成 JSON 的服务层.)
I'm using Spring MVC for a simple JSON API, with @ResponseBody
based approach like the following. (I already have a service layer producing JSON directly.)
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public 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 错误的最简单、最干净的方法是什么?
Question is, in the given scenario, what is the simplest, cleanest way to respond with a HTTP 400 error?
我确实遇到过以下方法:
I did come across approaches like:
return new ResponseEntity(HttpStatus.BAD_REQUEST);
...但我不能在这里使用它,因为我的方法的返回类型是字符串,而不是 ResponseEntity.
...but I can't use it here since my method's return type is String, not ResponseEntity.
推荐答案
把你的返回类型改成ResponseEntity<>
,然后你就可以用下面的400
change your return type to ResponseEntity<>
, then you can use below for 400
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
为了正确的请求
return new ResponseEntity<>(json,HttpStatus.OK);
更新 1
在 spring 4.1 之后,ResponseEntity 中的辅助方法可以用作
after spring 4.1 there are helper methods in ResponseEntity could be used as
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
和
return ResponseEntity.ok(json);
这篇关于如何在返回字符串的 Spring MVC @ResponseBody 方法中响应 HTTP 400 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!