Return HTTP 204 on null with spring @RestController

前端 未结 7 2014
旧时难觅i
旧时难觅i 2020-12-25 12:10

This returns 200 OK with Content-Length: 0

@RestController
public class RepoController {
    @RequestMapping(value = \"/document/{id}\", method = RequestMeth         


        
7条回答
  •  一整个雨季
    2020-12-25 13:07

    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(HttpStatus.NO_CONTENT);
           }
    
           return object ;
        }
    }
    

    Might have typos, but you get the concept.

提交回复
热议问题