利用注解@RestControllerAdvice拦截所有的ajax请求,构造统一格式的返回值
/**
* @desc 统一的响应结构
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResponse<T> implements Serializable {
private Integer code;
private String message;
private T data;
public CommonResponse(Integer code, String message) {
this.code = code;
this.message = message;
}
}
配置拦截
/**
* @desc 对响应的统一拦截,把所有响应弄成同一个格式
**/
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
//通过方法参数得到类名, 然后得到类上的annotation,
// 如果被IgnoreResponseAdvice标识就不拦截
if (methodParameter.getDeclaringClass().isAnnotationPresent(
IgnoreResponseAdvice.class
)){
return false;
}
//方法上被标注,也不拦截
if (methodParameter.getMethod().isAnnotationPresent(
IgnoreResponseAdvice.class
)){
return false;
}
return true;
}
//在写入响应之前,所以在这里构造统一格式
@Override
@Nullable
public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
CommonResponse<Object> response = new CommonResponse<>(0, "");
if (null == o) {
return response;
} else if (o instanceof CommonResponse) {
response = (CommonResponse<Object>) o;
} else {
response.setData(o);
}
return response;
}
}
有时候有些简单的注解,不需要统一的格式,就使用这个自定义的注解
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreResponseAdvice {
}
另外,同一个原理,可以进行统一异常处理
/**
* @desc 统一的异常处理 可以自己多定义几个异常类,细化,然后多建立几个方法使用@ExceptionHandler注解,处理特定的异常
**/
@RestControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler(value = GlobeException.class)
public CommonResponse<String> handlerGlobeException(HttpServletRequest request, GlobeException exception){
CommonResponse<String> response=new CommonResponse<>(-1,"");
response.setData(exception.getMessage());
return response;
}
}
public class GlobeException extends Exception {
public GlobeException(String message) {
super(message);
}
}
网友评论