且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-26 06:08:46

把你的返回类型改成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);