No Content in Spring Boot Rest

醉酒当歌 提交于 2019-12-20 03:09:03

问题


How do I configure Spring Boot to return 204 in GET methods (typically findAll methods) when the method does not fetch records? I would not like to do treatment in each method, type the code below:

if(!result)
    return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
    return new ResponseEntity<Void>(HttpStatus.OK)

I'd like to transform this method:

@GetMapping
public ResponseEntity<?> findAll(){
    List<User> result = service.findAll();
    return !result.isEmpty() ? 
            new ResponseEntity<>(result, HttpStatus.OK) : new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}

In this one:

@GetMapping
public List<User> findAll(){
    return service.findAll();
}

If the result from findAll() is empty or null then my controller should return 204 instead of 200.


回答1:


You could register a custom ResponseBodyAdvice which allows customizing the response of @ResponseBody or ResponseEntity handler methods (right before the content is being serialized by a MessageConverter):

@ControllerAdvice
class NoContentControllerAdvice implements ResponseBodyAdvice<List<?>> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return List.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public List<?> beforeBodyWrite(List<?> body, MethodParameter returnType, MediaType selectedContentType,
               Class<? extends HttpMessageConverter<?>> selectedConverterType,
               ServerHttpRequest request, ServerHttpResponse response) {

        if (body.isEmpty()) {
            response.setStatusCode(HttpStatus.NO_CONTENT);
        }
        return body;
    }
}


来源:https://stackoverflow.com/questions/49818918/no-content-in-spring-boot-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!