Spring AOP 后置通知修改响应httpstatus
1.定义Aspect
/**
* 响应体切面
* 后置通知修改httpstatus
*
* @author : CatalpaFlat
*/
@Component
@Aspect
public class ApiResponseAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 切面
*/
private final String POINT_CUT = "execution(* com.xxx.web.controller..*(..))";
@Pointcut(POINT_CUT)
private void pointcut() {
}
@AfterReturning(value = POINT_CUT, returning = "apiResponse", argNames = "apiResponse")
public void doAfterReturningAdvice2(ApiResponse apiResponse) {
logger.info("apiResponse:" + apiResponse);
Integer state = apiResponse.getState();
if (state != null) {
ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
res.getResponse().setStatus(state);
}
}
}
2.使用
2.1.请求体
return ApiUtil.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"the request body is empty");
2.2.参数缺失
return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"Parameter id is empty");
2.3.权限认证
return ApiUtil.error(HttpStatus.UNAUTHORIZED.value(),"Current requests need user validation");
2.4.与资源存在冲突
return ApiUtil.error(HttpStatus.CONFLICT.value(),"Conflict with resources");
2.5.携带error信息
return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"There are some mistakes",obj);
3.ApiResponse响应体
public class ApiResponse {
private Integer state;
private String message;
private Object result;
private Object error;
}
4.ApiUtil
public class ApiUtil {
/**
* http回调错误
*/
public static ApiResponse error(Integer code, String msg) {
ApiResponse result = new ApiResponse();
result.setState(code);
result.setMessage(msg);
return result;
}
/**
* http回调错误
*/
public static ApiResponse error(Integer code, String msg,Object error) {
ApiResponse result = new ApiResponse();
result.setState(code);
result.setMessage(msg);
result.setError(error);
return result;
}
}