如何在返回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。
3 回答

墨色風雨
TA貢獻1853條經驗 獲得超6個贊
將您的退貨類型更改為ResponseEntity<>
,然后您可以使用以下400
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
并提出正確的要求
return new ResponseEntity<>(json,HttpStatus.OK);
更新1
在4.1之后,ResponseEntity中有輔助方法可以用作
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
和
return ResponseEntity.ok(json);
添加回答
舉報
0/150
提交
取消