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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM