最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot項(xiàng)目如何使用切面記錄用戶操作日志

 更新時(shí)間:2022年10月31日 12:08:13   作者:WoddenFish  
這篇文章主要介紹了springboot項(xiàng)目如何使用切面記錄用戶操作日志,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

1、引入springboot-aop集成jar

Spring-boot-start-aop

2、application.yml中啟用聲明

#spring配置
spring:
  #切面啟用
  aop:
    proxy-target-class: true
    auto: true

3、自定義一個(gè)攔截controller的注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定義注解,攔截controller
 */
 
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在參數(shù)和方法上
@Retention(RetentionPolicy.RUNTIME)//運(yùn)行時(shí)注解
@Documented//表明這個(gè)注解應(yīng)該被 javadoc工具記錄
public @interface SystemControllerLog {
    String description() default "";
}

4、自定義一個(gè)攔截service的注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定義注解,攔截service
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}

5、定義日志記錄切面

package cn.annotation;
 
import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description: 切點(diǎn)類
 */
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用于把日志保存數(shù)據(jù)庫,實(shí)際項(xiàng)目入庫采用隊(duì)列做異步
    @Resource
    private ActionService actionService;
    //本地異常日志記錄對(duì)象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service層切點(diǎn)
    @Pointcut("@annotation(cn.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }
 
    //Controller層切點(diǎn)
    @Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }
 
    /**
     * @Description  前置通知  用于攔截Controller層記錄用戶的操作
     * @date 2018年9月3日 10:38
     */
 
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //讀取session中的用戶
        User user = (User) session.getAttribute("user");
 
        String ip = IpUtils.getIpAddr(request);
 
        try {
            //*========控制臺(tái)輸出=========*//
            System.out.println("==============前置通知開始==============");
            System.out.println("請(qǐng)求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
            System.out.println("請(qǐng)求人:"+user.getUsername());
            System.out.println("請(qǐng)求ip:"+ip);
 
            //*========數(shù)據(jù)庫日志=========*//
            Action action = new Action();
            action.setActionDes(getControllerMethodDescription(joinPoint));
            action.setActionType("0");
            action.setActionIp(ip);
            action.setUserId(user.getId());
            action.setActionTime(new Date());
            //保存數(shù)據(jù)庫
            actionService.add(action);
 
        }catch (Exception e){
            //記錄本地異常日志
            logger.error("==前置通知異常==");
            logger.error("異常信息:{}",e.getMessage());
        }
    }
 
    /**
     * @Description  異常通知 用于攔截service層記錄異常日志
     * @date 2018年9月3日 下午5:43
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //讀取session中的用戶
        User user = (User) session.getAttribute("user");
        //獲取請(qǐng)求ip
        String ip = IpUtils.getIpAddr(request);
        //獲取用戶請(qǐng)求方法的參數(shù)并序列化為JSON格式字符串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            /*========控制臺(tái)輸出=========*/
            System.out.println("=====異常通知開始=====");
            System.out.println("異常代碼:" + e.getClass().getName());
            System.out.println("異常信息:" + e.getMessage());
            System.out.println("異常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("請(qǐng)求人:" + user.getUsername());
            System.out.println("請(qǐng)求IP:" + ip);
            System.out.println("請(qǐng)求參數(shù):" + params);
            /*==========數(shù)據(jù)庫日志=========*/
            Action action = new Action();
            action.setActionDes(getServiceMethodDescription(joinPoint));
            action.setActionType("1");
            action.setUserId(user.getId());
            action.setActionIp(ip);
            action.setActionTime(new Date());
            //保存到數(shù)據(jù)庫
            actionService.add(action);
        }catch (Exception ex){
            //記錄本地異常日志
            logger.error("==異常通知異常==");
            logger.error("異常信息:{}", ex.getMessage());
        }
    }
 
 
    /**
     * @Description  獲取注解中對(duì)方法的描述信息 用于service層注解
     * @date 2018年9月3日 下午5:05
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
 
 
 
    /**
     * @Description  獲取注解中對(duì)方法的描述信息 用于Controller層注解
     * @date 2018年9月3日 上午12:01
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目標(biāo)方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}

6、開始使用

1)@SystemControllerLog(description = "")

注解加在控制器中方法上面,括號(hào)里寫上操作描述

2)用于監(jiān)控service異常,可以不使用

@SystemServiceLog(description = "")

注解加在service層方法上面,括號(hào)里寫上操作描述

(此處為AOP攔截Service記錄異常信息。方法不需要加try-catch)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java中刪除 數(shù)組中的指定元素方法

    java中刪除 數(shù)組中的指定元素方法

    下面小編就為大家?guī)硪黄猨ava中刪除 數(shù)組中的指定元素方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • Java Lambda表達(dá)式和函數(shù)式接口實(shí)例分析

    Java Lambda表達(dá)式和函數(shù)式接口實(shí)例分析

    這篇文章主要介紹了Java Lambda表達(dá)式和函數(shù)式接口,結(jié)合實(shí)例形式分析了Java8 Lambda表達(dá)式和函數(shù)式接口相關(guān)原理、用法及操作注意事項(xiàng),需要的朋友可以參考下
    2019-09-09
  • Easycode自動(dòng)化springboot的curd

    Easycode自動(dòng)化springboot的curd

    這篇文章主要介紹了Easycode自動(dòng)化springboot的curd,圍繞主題的相關(guān)資料展開詳細(xì)內(nèi)容,具有一定的參考價(jià)值,需要的小伙伴可以參考一下,希望給對(duì)你有所幫助
    2022-01-01
  • 淺談Maven鏡像更換為阿里云中央倉庫(精)

    淺談Maven鏡像更換為阿里云中央倉庫(精)

    本篇文章主要介紹了Maven鏡像更換為阿里云中央倉庫(精),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • java封裝類型與基礎(chǔ)類型對(duì)比示例分析

    java封裝類型與基礎(chǔ)類型對(duì)比示例分析

    這篇文章主要為大家介紹了java封裝類型與基礎(chǔ)類型對(duì)比示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • 23種設(shè)計(jì)模式(16)java訪問者模式

    23種設(shè)計(jì)模式(16)java訪問者模式

    這篇文章主要為大家詳細(xì)介紹了23種設(shè)計(jì)模式之java訪問者模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • SpringData JPA中@OneToMany和@ManyToOne的用法詳解

    SpringData JPA中@OneToMany和@ManyToOne的用法詳解

    這篇文章主要介紹了SpringData JPA中@OneToMany和@ManyToOne的用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java中的gateway自定義過濾器詳解

    Java中的gateway自定義過濾器詳解

    這篇文章主要介紹了Java中的gateway自定義過濾器詳解,過濾器是指gateway在路由過程中(A地址路由到B地址)生效進(jìn)行過濾操作的,所有首先你得先配一個(gè)地址路由,本文提供了部分實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2023-11-11
  • 淺析java中Integer傳參方式的問題

    淺析java中Integer傳參方式的問題

    以下是對(duì)java中Integer傳參方式的問題進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下
    2013-09-09
  • java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離

    java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離

    java實(shí)現(xiàn)計(jì)算地理坐標(biāo)之間的距離,主要是通過計(jì)算兩經(jīng)緯度點(diǎn)之間的距離來實(shí)現(xiàn),有需要的小伙伴參考下吧
    2015-03-03

最新評(píng)論

无为县| 罗定市| 准格尔旗| 平江县| 莱芜市| 巍山| 城口县| 嘉祥县| 阜宁县| 卢龙县| 莫力| 松原市| 昆山市| 梅州市| 湟中县| 海兴县| 达拉特旗| 文化| 安泽县| 东乌珠穆沁旗| 酒泉市| 辛集市| 华阴市| 宝坻区| 东安县| 施秉县| 田林县| 绥宁县| 许昌市| 西乌珠穆沁旗| 临洮县| 武强县| 皋兰县| 奉新县| 景谷| 上高县| 府谷县| 长岛县| 松潘县| 朝阳市| 丹棱县|