Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Java by (3.4k points)

I'm using Spring MVC for a simple JSON API, with @ResponseBody based approach like the following. (I already have a service layer producing JSON directly.)

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")

@ResponseBody

public 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;

}

Question is, in the given scenario, what is the simplest, cleanest way to respond with a HTTP 400 error?

I did come across approaches like:

return new ResponseEntity(HttpStatus.BAD_REQUEST);

...but I can't use it here since my method's return type is String, not ResponseEntity.

1 Answer

0 votes
by (46k points)

replace your return type to ResponseEntity<>, then you can apply following for 400

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

and for correct request

return new ResponseEntity<>(json,HttpStatus.OK);

following spring 4.1 there are assistant practices in ResponseEntity could be practiced as

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);

and

return ResponseEntity.ok(json);

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...