SpringBoot项目全局处理接口返回JSON数据

我们在提供 API json 数据接口时每个接口都需要返回 {code : 0,status:200,message:"",result:{} }之类的数据这些数据是重复的,我们可以利用Spring的AOP 去添加这些数据,Controller 中只返回有用的数据,如参数之类的错误可以直接返回null ,如有需要提示APP页面弹出的信息,直接加入到 result json 对象中 交给AOP 去格式化这个数据

1. SpringBoot 项目引入AOP

<!-- AOP -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.  创建AOP类

@Aspect
@Component
public class ResultAop {

   private static final Logger log = LoggerFactory.getLogger(ResultAop.class);

   private final String pointcutStr = "execution( * com.khsct.controller..*.*(..))";

   @Pointcut(pointcutStr)
   public void excuteController() {

   }

   @AfterReturning(value = pointcutStr, returning = "jobj")
   public JSONObject doAroundAdvice(JoinPoint joinPoint, JSONObject jobj) {
      // proceedingJoinPoint.getArgs();
      try {
         // obj之前可以写目标方法执行前的逻辑
         procesResultObj(jobj);
         return jobj;
      } catch (Throwable throwable) {
         throwable.printStackTrace();
         log.error("@AfterReturning 出错{}", throwable.getMessage());
      }
      return null;
   }

   /**
    * 处理返回对象
    */
   @SuppressWarnings("unused")
   private void procesResultObj(JSONObject obj) {
      if (obj != null) {
         String message = (String) obj.get(CommonConst.DEFAULT_MSG_POP_KEY);
         Integer code = ErrorCode.LOGIC_SUCCESS.getName();
         if (message != null) {
            code = ErrorCode.POP_MSG_CODE.getName();
            obj.remove(CommonConst.DEFAULT_MSG_POP_KEY);
         } else {
            message = ErrorMesg.Success.getName();
         }
         String str = JSON.toJSONString(obj);
         obj.clear();
         obj.put(CommonConst.DEFAULT_RESULT_STATUS_KEY, ErrorCode.SUCCESS.getName());
         obj.put(CommonConst.DEFAULT_RESULT_CODE_KEY, code);
         obj.put(CommonConst.DEFAULT_MSG_POP_KEY, message);
         obj.put(CommonConst.DEFAULT_RESULT_DATA_KEY, JSON.parseObject(str));
      }else{
         HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
         try {
            response.setCharacterEncoding(CommonConst.CHARACTER_ENCODING);
            response.setContentType(CommonConst.CONTENT_TYPE);
            ServletOutputStream out = out = response.getOutputStream();
            JSONObject o = new JSONObject();
            o.put(CommonConst.DEFAULT_RESULT_CODE_KEY, ErrorCode.FAILED.getName());
            o.put(CommonConst.DEFAULT_RESULT_STATUS_KEY, ErrorCode.SUCCESS.getName());
            o.put(CommonConst.DEFAULT_MSG_POP_KEY, ErrorMesg.Parameters_Error.getName());
            out.write(o.toString().getBytes());
            out.flush();
            out.close();
         } catch (IOException e) {
            e.printStackTrace();
            log.error(" 返回值为 null 获取 response.getOutputStream 出错 ");
         }
      }
   }
}

3. 在SpringBoot 启动类上加上注解开启AOP

@EnableAspectJAutoProxy(proxyTargetClass = true)

4. 创建 Controller  返回值必须要与AOP中 doAroundAdvice 定义的类型一致 或者是他的子类此处统一使用alibaba 的fastJson JSONObject  对象

@PostMapping(value = "/test")
public JSONObject test(String adminHeadImage, HttpServletRequest request) {
   JSONObject data = null;
  if(StringUtils.isNotBank(adminHeadImage)){
      data = new JSONObject();
   //data.put(key,value);
   }
   return data;
}

 

结果如下:

{
  "code": 1,
  "data": {},
  "message": "ok",
  "status": 200
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值