Spring MVC中@ResponseBody方法中如何返回HTTP400错误呢?
下文笔者讲述ResponseBody注解返回http400代码的方法及示例分享
ResponseBody注解返回http400状态码的方法
借助ResponseEntity对象返回
在返回ResponseEntity时传入相应的状态码
注意事项
此种方法必须将返回类型设置为ResponseEntity类型
例:SpringMVC返回http400状态码
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
}
return json;
}
修改为
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public ResponseEntity match(@PathVariable String matchId) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
//或
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
return return new ResponseEntity<>(json,HttpStatus.OK);;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


