存入数据库,运用了SpringAop的知识。以下知识全靠自己理解,若有不当,请原谅。或者大家积极提出自己意见,我当虚心接受。
SpringAop 就是解决冗余代码,比如事务,日志处理等等。先要创建增强,切入点,将增强添加到切入点的过程中即可形成切面。意思即不改变原有代码逻辑的情况下,实现业务增强。
下面直接呈现代码 controller层
result对象包含用户的信息
@RequestMapping("/doLogin")
@AdminLogAnnotion("登陆完成了")
public SysResult doLogin(@RequestParam(name="userAccount",required=true) String userAccount,
@RequestParam(name="userPassword",required=true) String userPassword,HttpSession session) {
try {
SysResult result = loginservice.doLogin(userAccount, userPassword);
session.setAttribute("key",result); //往session中存储 SysResult对象
session.setAttribute("key1",userAccount); //往session中存储 userAccount
return result;
} catch (EmptyResultException e) {
e.printStackTrace();
return new SysResult(ErrorUtil.CODE5000, e.getMessage(), null);
}
}
自定义注解
/**
* 加在自定义注解上的注解 叫做元注解
* @Target 指定注解使用的范围
*/
@Target(ElementType.METHOD) //在什么上使用注解 指定注解使用地方
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminLogAnnotion {
String value() default "";
}
写一个切面类
/**
* @Configuration 声明当前类为配置类 创建的bean放入中
* @Aspect 声明当前类为切面类
*/
@Configuration
@Aspect
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Autowired
private ZZLogServcie zzLogServcie;
/**
* 1.创建一个切点 切点设置在注解上
*/
@Pointcut("@annotation(com.zzmj.annotaion.AdminLogAnnotion)")
public void logPointCut(){}
/**
* 2.创建增强
*/
@After("logPointCut()")
public void logAfter(JoinPoint joinPoint){
logger.info("开始执行日志记录增强");
// 1.创建Log对象 赋值
Log log = new Log();
// 2.获取session中的对象
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpSession session = requestAttributes.getRequest().getSession();
LoginResult user= (LoginResult) ((SysResult) session.getAttribute("key")).getData();
String userAccount= (String) session.getAttribute("key1");
// 3.通过工具类获取ip
String ipAddrByRequest = IPKit.getIpAddrByRequest(requestAttributes.getRequest());
try {
if(null==user || "".equals(user)){
log.setId(CodeUtil.createUuid36());
log.setUserId("");
log.setUserName(userAccount);
log.setLoginIp(ipAddrByRequest);
log.setLoginTime(String.valueOf(System.currentTimeMillis()));
log.setLoginFlag(Integer.valueOf(0));
zzLogServcie.insert(log);
logger.info("用户登录失败!!!"+log); //这里需要对Log实体类进行toString方法
}else{
log.setId(CodeUtil.createUuid36());
log.setUserId(user.getUserId());
log.setUserName(user.getUserName());
log.setLoginIp(ipAddrByRequest);
log.setLoginTime(String.valueOf(System.currentTimeMillis()));
log.setLoginFlag(Integer.valueOf(1));
zzLogServcie.insert(log);
logger.info("用户登录成功!!!"+log); //这里需要对Log实体类进行toString方法
}
}catch (Exception e){
e.printStackTrace();
logger.info("添加日志出现异常!!!");
}
/*
// 4.通过获取当前方法上的注解 得到日志的内容
// 获取方法签名对象
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获得当前方法对象
Method method = signature.getMethod();
// 获取加在当前方法上的注解
AdminLogAnnotion annotation = method.getAnnotation(AdminLogAnnotion.class);
String value = annotation.value();*/
//log.setLogContent(value);
/*logger.info("结束记录增强"+log);*/
// 占位符的方式打印日志 在字符串中 写一个{} 后面使用逗号
// 只能在logger打印中使用
/*logger.info("结束记录增强:{}和{}",log,log);*/
// 插入数据库
//System.out.println(log+"+++++++");
}
}
获取IP的工具类
import javax.servlet.http.HttpServletRequest;
public class IPKit {
/**
* @param request 请求
* @return IP Address
*/
public static String getIpAddrByRequest(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
库表设计
这样就可将用户信息保存到数据库中,再次强调,运用了SpringAop,下面将用户登录信息作为日志保存到文件中,给大家展示一下logj.properties
log4j.rootLogger = InFo,stdout,UMRI
log4j.logger.org.springframework.boot.autoconfigure=ERROR
#配置日志输出信息
log4j.logger.com.zzmj.mapper=TRACE
#log4j.logger.druid.sql=ERROR,stdout,UMRD,UMRI,UMRE,DATABASE
#log4j.logger.druid.sql.DataSource=DEBUG,stdout,UMRD,UMRI,UMRE,DATABASE
#log4j.logger.druid.sql.Connection=DEBUG,stdout,UMRD,UMRI,UMRE,DATABASE
#log4j.logger.druid.sql.Statement=DEBUG,stdout,UMRD,UMRI,UMRE,DATABASE
#log4j.logger.druid.sql.ResultSet=DEBUG,stdout,UMRD,UMRI,UMRE,DATABASE
### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold = DEBUG
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c : %L - %m%n
#debug
log4j.appender.UMRD = org.apache.log4j.DailyRollingFileAppender
log4j.appender.UMRD.File = ../Log/Debug/debug.log
log4j.appender.UMRD.Append = true
log4j.appender.UMRD.Threshold = DEBUG
log4j.appender.UMRD.ImmediateFlush=true
log4j.appender.UMRD.DatePattern='_'yyyy-MM-dd'.log'
#配置日志信息的格式
log4j.appender.UMRD.layout = org.apache.log4j.PatternLayout
log4j.appender.UMRD.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#### info 文件 ###
log4j.appender.UMRI = org.apache.log4j.DailyRollingFileAppender
log4j.appender.UMRI.File = ../Log/Info/info.log
log4j.appender.UMRI.Append = true
log4j.appender.UMRI.Threshold = INFO
log4j.appender.UMRI.ImmediateFlush=true
log4j.appender.UMRI.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.UMRI.layout = org.apache.log4j.PatternLayout
log4j.appender.UMRI.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#### ERROR 文件保存至 D://PDFPollingLog/error.log ###
log4j.appender.UMRE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.UMRE.File = ../Log/Error/error.log
log4j.appender.UMRE.Append = true
log4j.appender.UMRE.Threshold = ERROR
log4j.appender.UMRE.ImmediateFlush=true
log4j.appender.UMRE.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.UMRE.layout = org.apache.log4j.PatternLayout
log4j.appender.UMRE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
# 用于数据库
log4j.appender.DATABASE=com.zzmj.config.MyJDBCAppender
log4j.appender.DATABASE.Threshold = INFO
log4j.appender.DATABASE.URL=jdbc:mysql://115.28.91.111:3306/ZaoKuang?useUnicode=true&characterEncoding=utf8
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
log4j.appender.DATABASE.user=yydk
log4j.appender.DATABASE.password=zmj.yydk
log4j.appender.DATABASE.sql=insert into LOG4J(add_time,level,run_time,tread_name,msg,cls_name,cls_method) values(now(),'%p','%r','%t','%m%n','%c','%M')
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=%d - %c -%-4r [%t] %-5p %c %x - %m%n
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!