spring - How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
Framework & Platform/Spring 2014. 7. 9. 14:43How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
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'm new to Spring MVC, and this turned out somewhat non-obvious... 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.
Answers
change your return type to ResponseEntity<String>
, then you can use below for 400
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
and for correct request
return new ResponseEntity<String>(json,HttpStatus.OK);
Something like this should work, I'm not sure whether or not there is a simpler way:
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body,
HttpServletRequest request, HttpServletResponse response) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
}
return json;
}
source - http://stackoverflow.com/questions/16232833/how-to-respond-with-http-400-error-in-a-spring-mvc-responsebody-method-returnin
'Framework & Platform > Spring' 카테고리의 다른 글
spring data - redis example (0) | 2014.08.15 |
---|---|
spring - Get a file under WEB-INF using Spring(web-inf access) (0) | 2014.07.24 |
spring - velocity email(webmail in java) (0) | 2014.06.27 |
spring - Servlet 3 Async Config (0) | 2014.05.01 |
spring - spring mvc test (0) | 2014.04.17 |