import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// 判断是否为跨域请求及构建统一返回格式
if (RequestContextHolder.getRequestAttributes() != null) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String origin = attributes.getRequest().getHeader("Origin");
if (origin != null) {
response.getHeaders().set("Access-Control-Allow-Origin", origin);
response.getHeaders().set("Access-Control-Allow-Credentials", "true");
}
}
// 构建统一的返回格式
Result result = new Result();
if (body instanceof Result) {
result = (Result) body;
} else {
result.setData(body);
}
return result;
}
}
class Result<T> {
private int code;
private String message;
private T data;
// 省略getter和setter方法...
}
这个代码实例展示了如何在Spring Boot应用中使用@ControllerAdvice
和ResponseBodyAdvice
来实现全局的响应处理,统一输出格式。在beforeBodyWrite
方法中,我们首先判断是否为跨域请求,并对响应头进行设置,然后构建统一的返回结果格式。这样,每个响应体都会被处理,并且添加了统一的格式,方便客户端处理。