问题
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