What to return if Spring MVC controller method doesn't return value?
you can return void, then you have to mark the method with @ResponseStatus(value = HttpStatus.OK) you don't need @ResponseBody
@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
...
}
Only get methods return a 200 status code implicity, all others you have do one of three things:
- Return void and mark the method with
@ResponseStatus(value = HttpStatus.OK)
- Return An object and mark it with
@ResponseBody
- Return an
HttpEntity
instance
You can simply return a ResponseEntity with the appropriate header:
@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}
You can return "ResponseEntity" object. Using "ResponseEntity" object is very convenient both at the time of constructing the response object (that contains Response Body and HTTP Status Code) and at the time of getting information out of the response object.
Methods like getHeaders(), getBody(), getContentType(), getStatusCode() etc makes the work of reading the ResponseEntity object very easy.
You should be using ResponseEntity object with a http status code of 204(No Content), which is specifically to specify that the request has been processed properly and the response body is intentionally blank. Using appropriate Status Codes to convey the right information is very important, especially if you are making an API that is going to be used by multiple client applications.