|
|
@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
package com.example.api.handler;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 导入自定义的禁止基础响应注解
|
|
|
|
|
|
|
|
import com.example.api.annotation.DisableBaseResponse;
|
|
|
|
|
|
|
|
// 导入用于封装API响应结果的类
|
|
|
|
|
|
|
|
import com.example.api.model.support.ResponseResult;
|
|
|
|
|
|
|
|
// 导入Spring的MethodParameter类,用于获取方法参数信息
|
|
|
|
|
|
|
|
import org.springframework.core.MethodParameter;
|
|
|
|
|
|
|
|
// 导入Spring的MediaType类,用于表示媒体类型
|
|
|
|
|
|
|
|
import org.springframework.http.MediaType;
|
|
|
|
|
|
|
|
// 导入Spring的ServerHttpRequest和ServerHttpResponse类,用于处理HTTP请求和响应
|
|
|
|
|
|
|
|
import org.springframework.http.server.ServerHttpRequest;
|
|
|
|
|
|
|
|
import org.springframework.http.server.ServerHttpResponse;
|
|
|
|
|
|
|
|
// 导入Spring MVC的@ControllerAdvice注解,用于定义全局的控制器增强
|
|
|
|
|
|
|
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
|
|
|
|
|
|
// 导入Spring MVC的ResponseBodyAdvice接口,用于在响应写入前进行处理
|
|
|
|
|
|
|
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
|
|
* 统一拦截Controller中所有方法的返回值
|
|
|
|
|
|
|
|
* 封装后返回ResponseResult<T>
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
@ControllerAdvice(value = "com.example.api.controller")
|
|
|
|
|
|
|
|
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 实现supports方法,判断当前方法是否需要被增强
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
|
|
|
public boolean supports(MethodParameter methodParameter, Class c) {
|
|
|
|
|
|
|
|
// 如果方法参数上有DisableBaseResponse注解,则不进行增强
|
|
|
|
|
|
|
|
return !methodParameter.hasParameterAnnotation(DisableBaseResponse.class);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 实现beforeBodyWrite方法,在响应写入前进行处理
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
|
|
|
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
|
|
|
|
|
|
|
|
ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
|
|
|
|
|
|
|
|
// 如果返回值为null,则返回一个空的ResponseResult对象
|
|
|
|
|
|
|
|
// 否则,将返回值封装在ResponseResult对象中
|
|
|
|
|
|
|
|
return o == null ? new ResponseResult<>() : new ResponseResult<>(o);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|