user1606576 user1606576 - 22 days ago 10
Java Question

Return HTTP 204 on null with spring @RestController

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

Answer

Of course yes.

Option 1 :

@RestController
public class RepoController {
    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
    public Object getDocument(@PathVariable long id, HttpServletResponse response) {
       Object object = getObject();
       if( null == object ){
          response.setStatus( HttpStatus.SC_NO_CONTENT);
       }
       return object ;
    }}

Option 2 :

@RestController
    public class RepoController {
        @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
        public Object getDocument(@PathVariable long id) {
           Object object = getObject();
           if( null == object ){
              return new ResponseEntity<String>(HttpStatus.SC_NO_CONTENT);
           }

           return object ;
        }}

Might have typos, but you get the concept.

Comments