JAVA全系列 教程
3762个小节阅读:7089.9k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
xxxxxxxxxx
package com.bjsxt.aspectj.annotation;
import com.bjsxt.aspectj.enums.BusinessType;
import com.bjsxt.aspectj.enums.OperatorType;
import java.lang.annotation.*;
/**
* 自定义操作日志记录注解
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
}
xxxxxxxxxx
package com.bjsxt.utils;
import ...
/**
*
*/
public class ServletUtils {
/**
* 获取request
*/
public static HttpServletRequest getRequest(){
return getRequestAttributes().getRequest();
}
public static ServletRequestAttributes getRequestAttributes(){
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
}
xxxxxxxxxx
package com.bjsxt.aspectj;
import ...
/**
*
*/
@Component
@Aspect
@Log4j2
public class OperLogAspect {
@Autowired
private OperLogService operLogService; //保存日志的接口
/**
* 声明切面
* 只要Controller的方法里面有@Log这个一样注解,那我就要切入
*/
@Pointcut("@annotation(com.bjsxt.aspectj.annotation.Log)")
public void logPointCut() {}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e){
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult){
try{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null){
return;
}
// 获取当前的用户
User loginUser = ShiroSecurityUtils.getCurrentUser();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(String.valueOf(BusinessStatus.SUCCESS.ordinal()));
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
operLog.setOperIp(ip);
String address = AddressUtils.getRealAddressByIP(ip);
operLog.setOperLocation(address);
// 返回参数
operLog.setJsonResult(JSON.toJSONString(jsonResult));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (loginUser != null){
operLog.setOperName(loginUser.getUserName());
}
if (e != null){
operLog.setStatus(String.valueOf(BusinessStatus.FAIL.ordinal()));
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog);
//设置操作时间
operLog.setOperTime(DateUtil.date());
// 保存数据库
operLogService.insertOperLog(operLog);
}
catch (Exception exp){
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取请求的参数,放到log中
* @param joinPoint
* @param operLog
*/
private void setRequestValue(JoinPoint joinPoint, OperLog operLog) {
String requestMethod = operLog.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
{
String params = argsArrayToString(joinPoint.getArgs());
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
}
else
{
Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
}
}
/**
* 是否存在注解,如果存在就获取
* @param joinPoint
* @return
*/
private Log getAnnotationLog(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null){
return method.getAnnotation(Log.class);
}
return null;
}
}
在LoginController中的退出登录方法加上切面注解
xxxxxxxxxx
/**
* 用户退出
*/
@PostMapping("login/logout")
@Log(title = "用户退出",businessType = BusinessType.OTHER)
public AjaxResult logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return AjaxResult.success("用户退出成功");
}
DictTypeController中的操作字典数据的方法增加切面方法
xxxxxxxxxx
/**
* 添加
*/
@PostMapping("addDictType")
@Log(title = "添加字典类型",businessType = BusinessType.INSERT)
public AjaxResult addDictType(@Validated DictTypeDto dictTypeDto) {
if (dictTypeService.checkDictTypeUnique(dictTypeDto.getDictId(), dictTypeDto.getDictType())) {
return AjaxResult.fail("新增字典【" + dictTypeDto.getDictName() + "】失败,字典类型已存在");
}
dictTypeDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
return AjaxResult.toAjax(this.dictTypeService.insert(dictTypeDto));
}
/**
* 修改
*/
@PutMapping("updateDictType")
@Log(title = "修改字典类型",businessType = BusinessType.UPDATE)
public AjaxResult updateDictType(@Validated DictTypeDto dictTypeDto) {
if (dictTypeService.checkDictTypeUnique(dictTypeDto.getDictId(), dictTypeDto.getDictType())) {
return AjaxResult.fail("修改字典【" + dictTypeDto.getDictName() + "】失败,字典类型已存在");
}
dictTypeDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
return AjaxResult.toAjax(this.dictTypeService.update(dictTypeDto));
}
/**
* 根据ID查询一个字典信息
*/
@GetMapping("getOne/{dictId}")
public AjaxResult getDictType(@PathVariable @Validated @NotNull(message = "字典ID不能为空") Long dictId) {
return AjaxResult.success(this.dictTypeService.selectDictTypeById(dictId));
}
/**
* 删除
*/
@DeleteMapping("deleteDictTypeByIds/{dictIds}")
@Log(title = "删除字典类型",businessType = BusinessType.DELETE)
public AjaxResult updateDictType(@PathVariable @Validated @NotEmpty(message = "要删除的ID不能为空") Long[] dictIds) {
return AjaxResult.toAjax(this.dictTypeService.deleteDictTypeByIds(dictIds));
}
/**
* 同步字典数据到redis
*/
@GetMapping("dictCacheAsync")
@Log(title = "同步字典数据到redis",businessType = BusinessType.OTHER)
public AjaxResult dictCacheAsync(){
try {
this.dictTypeService.dictCacheAsync();
return AjaxResult.success();
}catch (Exception e){
System.out.println(e);
return AjaxResult.error();
}
}