spring mvc统一处理接口返回值,aop切面实现,将请求的入参和出参存储在数据库中,切面内重新抛出异常

spring mvc统一处理接口返回值,aop切面实现,将请求的入参和出参存储在数据库中

aop类实现
Aspect的多个方法注解中,只有Around注解的方法是有返回值的,可以对方法的入参和返回值均进行操作。
@Before 在切点方法之前执行
@After 在切点方法之后执行
@AfterReturning 切点方法返回后执行
@AfterThrowing 切点方法抛异常执行
@Around 属于环绕增强,能控制切点执行前,执行后,,用这个注解后,程序抛异常,会影响@AfterThrowing这个注解

 

关键操作和逻辑如下[思路]:
1.建表

CREATE TABLE `sys_log` (
`ID` int(20) NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(50) DEFAULT NULL,
`OPERATION` varchar(50) DEFAULT NULL,
`LOGTIME` int(11) DEFAULT NULL,
`METHOD` varchar(200) DEFAULT NULL,
`PARAMS` varchar(500) DEFAULT NULL,
`IP` varchar(64) DEFAULT NULL,
`CREATE_TIME` date DEFAULT NULL,
`RESP` varchar(300) DEFAULT NULL,
KEY `ID` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

 

2.创建注解

package com.springboot.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String value() default "";
}

 


3.切面处理类

package com.springboot.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import com.springboot.annotation.Log;
import com.springboot.dao.SysLogDao;
import com.springboot.domain.SysLog;
import com.springboot.util.HttpContextUtils;
import com.springboot.util.IPUtils;
import sun.rmi.transport.ObjectTable;

/**
 *
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysLogDao sysLogDao;

    @Pointcut("@annotation(com.springboot.annotation.Log)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        long beginTime = System.currentTimeMillis();
        //增加返回值
        Object proceed = null;
        try {
            // 执行方法
            proceed = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time,proceed);
        //关键,同时该参数作为入参存储在数据库中。
        return proceed;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time, Object proceed) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        Log logAnnotation = method.getAnnotation(Log.class);
        if (logAnnotation != null) {
            // 注解上的描述
            sysLog.setOperation(logAnnotation.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                System.out.println(i+" paramNames[i]="+paramNames[i]+",args[i]="+args[i]);
                params += "  " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        // 模拟一个用户名
        sysLog.setUsername("system-test");
        sysLog.setTime((int) time);
        Date date = new Date();
        sysLog.setCreateTime(date);

        //查询返回值
        System.out.println("target=" + joinPoint.getTarget());
        System.out.println("kind=" + joinPoint.getKind());
        System.out.println("proceed=" + proceed.toString());  //返回结果
        sysLog.setResp(proceed.toString());

        // 保存系统日志
        sysLogDao.saveSysLog(sysLog);
    }
}

 

4.控制器

@RestController
public class TestController {
    @Log("执行方法test")
    @GetMapping("/test")
    public String test(String name, String age) {
        return "beijing-"+name+age;
    }


    @Log("执行方法四")
    @PostMapping(value="/four")
    @RequestMapping(value="four",method=RequestMethod.POST)
    public String methodFour(@RequestBody ParamModel model) {
        System.out.println("model="+model.toString() + "success!!") ;
        return "helloworld-response";
    }
}

 

5.其他的dao,model,sqlmapper略

————————————————
原文链接:https://blog.csdn.net/fengyujiancheng_93/article/details/103620409

posted on 2021-11-09 20:12  oktokeep  阅读(2002)  评论(1编辑  收藏  举报