Home > Java > javaTutorial > body text

How to respond with HTTP 400 \'Bad Request\' in Spring MVC @ResponseBody?

Barbara Streisand
Release: 2024-10-31 05:54:01
Original
348 people have browsed it

How to respond with HTTP 400

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>
Copy after login

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:

  1. Changing the Return Type to ResponseEntity: By changing the method's return type to ResponseEntity<>, you gain access to methods that allow you to set the HTTP status code. You can then use ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null) to return a 400 error response.
  2. Using ResponseEntity Helper Methods: For Spring versions 4.1 and higher, ResponseEntity provides helper methods such as ResponseEntity.badRequest().body(null) and ResponseEntity.ok(json) to simplify the response creation process.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!