一、创建一个注解,用于标记需要记录日志的方法。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginLog {
}
二、创建一个切面,用于记录日志。
@Aspect
@Component
public class LoginLogAspect {
@Autowired
private LoginLogService loginLogService;
@Pointcut("@annotation(com.example.demo.annotation.LoginLog)")
public void loginLog() {
}
@AfterReturning(pointcut = "loginLog()")
public void afterReturning(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LoginLog loginLogAnnotation = method.getAnnotation(LoginLog.class);
if (loginLogAnnotation != null) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getRemoteAddr();
String username = (String) request.getSession().getAttribute("username");
String description = loginLogAnnotation.description();
LoginLog loginLog = new LoginLog(ip, username, description);
loginLogService.saveLoginLog(loginLog);
}
}
}
在切面中,先定义一个切点,切点的表达式为被@LoginLog注解标记的方法。然后在afterReturning方法中获得方法的注解,从而获得description属性,然后从RequestContextHolder中获得HttpServletRequest,从而获取IP地址和用户名,最后将这些信息存储到LoginLog实体中,通过LoginLogService保存到数据库。
三、在需要记录日志的方法上添加@LoginLog(description = “登录”)注解。例如:
@PostMapping("/login")
@LoginLog(description = "登录")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
// ...
}
通过以上步骤,就可以实现在用户登录时记录登录日志。