亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1、設(shè)計(jì)用戶操作日志表: sys_oper_log
2、引入依賴
3、自定義用戶操作日志注解
4、自定義用戶操作日志切面
5、MyLog注解的使用
6、最終效果
Home Java javaTutorial How to use SpringBoot+Aop to record user operation logs

How to use SpringBoot+Aop to record user operation logs

May 11, 2023 pm 09:16 PM
aop springboot

1、設(shè)計(jì)用戶操作日志表: sys_oper_log

How to use SpringBoot+Aop to record user operation logs

對(duì)應(yīng)實(shí)體類為SysOperLog.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 * 操作日志記錄
 * </p>
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysOperLog implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    @ApiModelProperty("主鍵Id")
    private Integer id;

    @ApiModelProperty("模塊標(biāo)題")
    private String title;

    @ApiModelProperty("參數(shù)")
    private String optParam;

    @ApiModelProperty("業(yè)務(wù)類型(0其它 1新增 2修改 3刪除)")
    private Integer businessType;

    @ApiModelProperty("路徑名稱")
    private String uri;

    @ApiModelProperty("操作狀態(tài)(0正常 1異常)")
    private Integer status;

    @ApiModelProperty("錯(cuò)誤消息")
    private String errorMsg;

    @ApiModelProperty("操作時(shí)間")
    private Date operTime;
}

2、引入依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.9</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

3、自定義用戶操作日志注解

MyLog.java

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLog {
    // 自定義模塊名,eg:登錄
    String title() default "";
    // 方法傳入的參數(shù)
    String optParam() default "";
    // 操作類型,eg:INSERT, UPDATE...
    BusinessType businessType() default BusinessType.OTHER;  
}

BusinessType.java — 操作類型枚舉類

public enum BusinessType {
    // 其它
    OTHER,
    // 查找
    SELECT,
    // 新增
    INSERT,
    // 修改
    UPDATE,
    // 刪除
    DELETE,
}

4、自定義用戶操作日志切面

LogAspect.java

import com.alibaba.fastjson.JSONObject;
import iot.sixiang.license.entity.SysOperLog;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.service.SysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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.stereotype.Component;

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

@Aspect
@Component
@Slf4j
public class LogAspect {
    /**
     * 該Service及其實(shí)現(xiàn)類相關(guān)代碼請(qǐng)自行實(shí)現(xiàn),只是一個(gè)簡(jiǎn)單的插入數(shù)據(jù)庫(kù)操作
     */
    @Autowired
    private SysOperLogService sysOperLogService;
    
	/**
     * @annotation(MyLog類的路徑) 在idea中,右鍵自定義的MyLog類-> 點(diǎn)擊Copy Reference
     */
    @Pointcut("@annotation(xxx.xxx.xxx.MyLog)")
    public void logPointCut() {
        log.info("------>配置織入點(diǎn)");
    }

    /**
     * 處理完請(qǐng)求后執(zhí)行
     *
     * @param joinPoint 切點(diǎn)
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 攔截異常操作
     *
     * @param joinPoint 切點(diǎn)
     * @param e         異常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e) {

        // 獲得MyLog注解
        MyLog controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }
        SysOperLog operLog = new SysOperLog();
        // 操作狀態(tài)(0正常 1異常)
        operLog.setStatus(0);
        // 操作時(shí)間
        operLog.setOperTime(new Date());
        if (e != null) {
            operLog.setStatus(1);
            // IotLicenseException為本系統(tǒng)自定義的異常類,讀者若要獲取異常信息,請(qǐng)根據(jù)自身情況變通
            operLog.setErrorMsg(StringUtils.substring(((IotLicenseException) e).getMsg(), 0, 2000));
        }

        // UserUtils.getUri();獲取方法上的路徑 如:/login,本文實(shí)現(xiàn)方法如下:
        // 1、在攔截器中 String uri = request.getRequestURI();
        // 2、用ThreadLocal存放uri,UserUtils.setUri(uri);
        // 3、UserUtils.getUri();
        String uri = UserUtils.getUri();
        operLog.setUri(uri);
        // 處理注解上的參數(shù)
        getControllerMethodDescription(joinPoint, controllerLog, operLog);
        // 保存數(shù)據(jù)庫(kù)
        sysOperLogService.addOperlog(operLog.getTitle(), operLog.getBusinessType(), operLog.getUri(), operLog.getStatus(), operLog.getOptParam(), operLog.getErrorMsg(), operLog.getOperTime());
    }

    /**
     * 是否存在注解,如果存在就獲取,不存在則返回null
     * @param joinPoint
     * @return
     */
    private MyLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(MyLog.class);
        }
        return null;
    }

    /**
     * 獲取Controller層上MyLog注解中對(duì)方法的描述信息
     * @param joinPoint 切點(diǎn)
     * @param myLog 自定義的注解
     * @param operLog 操作日志實(shí)體類
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, MyLog myLog, SysOperLog operLog) {
        // 設(shè)置業(yè)務(wù)類型(0其它 1新增 2修改 3刪除)
        operLog.setBusinessType(myLog.businessType().ordinal());
        // 設(shè)置模塊標(biāo)題,eg:登錄
        operLog.setTitle(myLog.title());
        // 對(duì)方法上的參數(shù)進(jìn)行處理,處理完:userName=xxx,password=xxx
        String optParam = getAnnotationValue(joinPoint, myLog.optParam());
        operLog.setOptParam(optParam);

    }

    /**
     * 對(duì)方法上的參數(shù)進(jìn)行處理
     * @param joinPoint
     * @param name
     * @return
     */
    private String getAnnotationValue(JoinPoint joinPoint, String name) {
        String paramName = name;
        // 獲取方法中所有的參數(shù)
        Map<String, Object> params = getParams(joinPoint);
        // 參數(shù)是否是動(dòng)態(tài)的:#{paramName}
        if (paramName.matches("^#\\{\\D*\\}")) {
            // 獲取參數(shù)名,去掉#{ }
            paramName = paramName.replace("#{", "").replace("}", "");
            // 是否是復(fù)雜的參數(shù)類型:對(duì)象.參數(shù)名
            if (paramName.contains(".")) {
                String[] split = paramName.split("\\.");
                // 獲取方法中對(duì)象的內(nèi)容
                Object object = getValue(params, split[0]);
                // 轉(zhuǎn)換為JsonObject
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
                // 獲取值
                Object o = jsonObject.get(split[1]);
                return String.valueOf(o);
            } else {// 簡(jiǎn)單的動(dòng)態(tài)參數(shù)直接返回
                StringBuilder str = new StringBuilder();
                String[] paraNames = paramName.split(",");
                for (String paraName : paraNames) {
                    
                    String val = String.valueOf(getValue(params, paraName));
                    // 組裝成 userName=xxx,password=xxx,
                    str.append(paraName).append("=").append(val).append(",");
                }
                // 去掉末尾的,
                if (str.toString().endsWith(",")) {
                    String substring = str.substring(0, str.length() - 1);
                    return substring;
                } else {
                    return str.toString();
                }
            }
        }
        // 非動(dòng)態(tài)參數(shù)直接返回
        return name;
    }

    /**
     * 獲取方法上的所有參數(shù),返回Map類型, eg: 鍵:"userName",值:xxx  鍵:"password",值:xxx
    * @param joinPoint
     * @return
     */
    public Map<String, Object> getParams(JoinPoint joinPoint) {
        Map<String, Object> params = new HashMap<>(8);
        // 通過(guò)切點(diǎn)獲取方法所有參數(shù)值["zhangsan", "123456"]
        Object[] args = joinPoint.getArgs();
        // 通過(guò)切點(diǎn)獲取方法所有參數(shù)名 eg:["userName", "password"]
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] names = signature.getParameterNames();
        for (int i = 0; i < args.length; i++) {
            params.put(names[i], args[i]);
        }
        return params;
    }

    /**
     * 從map中獲取鍵為paramName的值,不存在放回null
     * @param map
     * @param paramName
     * @return
     */
    private Object getValue(Map<String, Object> map, String paramName) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals(paramName)) {
                return entry.getValue();
            }
        }
        return null;
    }
}

5、MyLog注解的使用

@GetMapping("login")
@MyLog(title = "登錄", optParam = "#{userName},#{password}", businessType = BusinessType.OTHER)
public DataResult login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
 ...
}

6、最終效果

How to use SpringBoot+Aop to record user operation logs

The above is the detailed content of How to use SpringBoot+Aop to record user operation logs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to use the @Import annotation in SpringBoot How to use the @Import annotation in SpringBoot May 31, 2023 pm 06:25 PM

1. @Import introduces ordinary classes @Import introduces ordinary classes can help us define ordinary classes as Beans. @Import can be added to the classes corresponding to @SpringBootApplication (startup class), @Configuration (configuration class), and @Component (component class). Note: @RestController, @Service, and @Repository all belong to @Component@SpringBootApplication@Import(ImportBean.class)//ImportBean through the @Import annotation

See all articles