当控制器方法响应类型为void
时,我尝试让spring自动返回HTTP状态204。例如:
让我们说我有一个像这样的控制器方法:
@DeleteMapping(value = "/{heroId}")
public void delete(@PathVariable Long heroId) {
heroService.delete(heroId);
}
我正在寻找一种自动返回204的方法,而无需使用@ResponseStatus(value = HttpStatus.NO_CONTENT)
注释该方法。
是否可以使用处理程序或AOP或其他工具执行此操作?
PS。我看到了这个答案Return HTTP 204 on null with spring @RestController,但没有回答我关于如何为void
返回类型的方法实现此问题的具体问题。此外,此方法应该使用没有输入参数的方法。
答案 0 :(得分:4)
我能够根据Yoshua提供的链接实施解决方案。我不是100%确定实施细节,但它对我有用。
这将捕获所有返回类型为void
的控制器方法的响应,并将其HTTP状态更改为204.
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
public class NoContentControllerAdvice implements ResponseBodyAdvice<Void> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
if(returnType.getParameterType().isAssignableFrom(void.class)) {
return true;
}
return false;
}
@Override
public Void beforeBodyWrite(Void body, MethodParameter returnType, MediaType mediaType,
Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {
if(returnType.getParameterType().isAssignableFrom(void.class)) {
response.setStatusCode(HttpStatus.NO_CONTENT);
}
return body;
}
}
答案 1 :(得分:1)
我看到这个问题已经得到解决,但是这种解决方案更加简洁:
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
public class NoContentControllerAdvice implements ResponseBodyAdvice<Void> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType() == void.class;
}
@Override
public Void beforeBodyWrite(Void body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
response.setStatusCode(HttpStatus.NO_CONTENT);
return body;
}
}