This returns 200 OK with Content-Length: 0
@RestController
public class RepoController {
@RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
public Object getDocument(@PathVariable long id) {
return null;
}
}
Simply put I'd like it to return 204 No Content on null.
Is there a way to force spring-mvc/rest to return 204 on null not 200? I dont want to change every rest method to return ResponseEntity or something like that, only map null to 204
Of course yes.
Option 1 :
Option 2 :
Might have typos, but you get the concept.
I solved this problem with a filter. It's global and simple.
and add the following in your web.xml
You can use the @ResponseStatus annotation. This way you can have a void method and you don't have to build a ResponseEntity.
BTW returning 200 when the object exists and 204 otherwise it's a bit unusual regarding API REST design. It's common to return a 404 (not found) when the requested object is not found. And this can be achieved using an ControllerAdvice.
In Spring REST it's better to handle Exceptions with a Exception handler instead of putting logic to decide the response status, etc. This is an example using the @ControllerAdvice annotation: http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service
You can try this :
Uou need to change HttpStatus.BAD_REQUEST with the equivalent for 204 code status
Question is old but for those that needs a global answer and have Spring 4+, you can create a ResponseBodyAdvice that changes response code base on the controller response. The following exemple do it for all @RestController classes :
Same answer but solved by AOP: