How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Change your return type to ResponseEntity<>, then you can use below for 400:

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

and for correct request

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

UPDATE 1

After Spring 4.1 there are helper methods in ResponseEntity could be used as

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

and

return ResponseEntity.ok(json);

Leave a Comment