Spring Boot Rest 中没有内容 [英] No Content in Spring Boot Rest
问题描述
如何配置 Spring Boot 在 GET 方法(通常是 findAll 方法)中不获取记录时返回 204?我不想在每种方法中都做处理,输入下面的代码:
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)
我想转换这个方法:
@GetMapping
public ResponseEntity<?> findAll(){
List<User> result = service.findAll();
return !result.isEmpty() ?
new ResponseEntity<>(result, HttpStatus.OK) : new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
在这个:
@GetMapping
public List<User> findAll(){
return service.findAll();
}
如果 findAll() 的结果为空或 null,那么我的控制器应该返回 204 而不是 200.
If the result from findAll() is empty or null then my controller should return 204 instead of 200.
推荐答案
你可以注册一个自定义的 ResponseBodyAdvice
允许自定义 @ResponseBody
或 ResponseEntity
处理程序方法(就在内容被 MessageConverter
序列化之前):
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;
}
}
这篇关于Spring Boot Rest 中没有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!