Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Content in Spring Boot Rest

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.

like image 483
Luciano Borges Avatar asked Sep 01 '25 21:09

Luciano Borges


1 Answers

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;
    }
}
like image 187
fateddy Avatar answered Sep 03 '25 10:09

fateddy