Responding with HTTP 400 Error in Spring MVC @ResponseBody
When developing JSON APIs using Spring MVC's @ResponseBody approach, there may be scenarios where you need to respond with specific HTTP status codes, such as 400 "Bad Request."
Consider the following action method:
<code class="java">@RequestMapping(value = "/matches/{matchId}", produces = "application/json") @ResponseBody public String match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { // How to respond with HTTP 400 "Bad Request"? } return json; }</code>
In this example, the method is annotated with @ResponseBody, indicating that the return value should be written directly to the HTTP response body. However, the initial code does not provide a mechanism for responding with an HTTP 400 error.
To resolve this issue, there are a couple of approaches to consider:
Therefore, the updated method would look like:
<code class="java">@RequestMapping(value = "/matches/{matchId}", produces = "application/json") @ResponseBody public ResponseEntity<String> match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { return ResponseEntity.badRequest().body(null); } return ResponseEntity.ok(json); }</code>
The above is the detailed content of How to respond with HTTP 400 \"Bad Request\" in Spring MVC @ResponseBody?. For more information, please follow other related articles on the PHP Chinese website!