springboot項(xiàng)目如何使用切面記錄用戶操作日志
1、引入springboot-aop集成jar
Spring-boot-start-aop
2、application.yml中啟用聲明
#spring配置
spring:
#切面啟用
aop:
proxy-target-class: true
auto: true3、自定義一個(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í)現(xiàn)提取不重復(fù)的整數(shù)實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)提取不重復(fù)的整數(shù)實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12
Sentinel實(shí)現(xiàn)動(dòng)態(tài)配置的集群流控的方法
這篇文章主要介紹了Sentinel實(shí)現(xiàn)動(dòng)態(tài)配置的集群流控,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Java簡易抽獎(jiǎng)系統(tǒng)小項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了Java簡易抽獎(jiǎng)系統(tǒng)小項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式
這篇文章主要介紹了SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
Java項(xiàng)目中防止SQL注入的四種方案總結(jié)
SQL注入是一種代碼注入技術(shù),通過把SQL命令插入到Web表單遞交或輸入域名或頁面請(qǐng)求的查詢字符串,最終達(dá)到欺騙服務(wù)器執(zhí)行惡意的SQL命令,下面我們就來看看如何在項(xiàng)目中防止SQL注入吧2023-10-10
Springboot設(shè)置文件上傳大小限制的實(shí)現(xiàn)示例
Spring Boot工程嵌入的tomcat限制了請(qǐng)求的文件大小默認(rèn)為1MB,單次請(qǐng)求的文件的總數(shù)不能大于10Mb,本文主要介紹了Springboot設(shè)置文件上傳大小限制的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-11-11
Trie樹(字典樹)的介紹及Java實(shí)現(xiàn)
Trie樹,又稱字典樹或前綴樹,關(guān)于它的結(jié)構(gòu)就不詳細(xì)介紹了。Trie樹在單詞統(tǒng)計(jì)、前綴匹配等很多方面有很大用處。下面這篇文章主要介紹了Trie樹,以及Java實(shí)現(xiàn)如何Trie樹,有需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
Spring Boot JPA如何把ORM統(tǒng)一起來
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規(guī)范的基礎(chǔ)上封裝的一套JPA應(yīng)用框架,可使開發(fā)者用極簡的代碼即可實(shí)現(xiàn)對(duì)數(shù)據(jù)的訪問和操作,本文給大家詳細(xì)介紹了Spring Boot JPA如何把ORM統(tǒng)一起來,感興趣的朋友一起看看吧2018-04-04
java容器類知識(shí)點(diǎn)詳細(xì)總結(jié)
這篇文章主要介紹了java容器類知識(shí)點(diǎn)詳細(xì)總結(jié),2019-06-06

