如何在返回String的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);
...但我不能在这里使用它,因为我的方法的返回类型是String,而不是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);
这篇关于如何在返回String的Spring MVC @ResponseBody方法中响应HTTP 400错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!