这是我参与 8 月更文挑战的第 19 天,活动详情查看: 8月更文挑战
之前通过AOP实现日志管理中包括了当前登录人、类名、方法名、参数以及执行时间共5个字段,现在根据需求,需要添加一个当前登录ip字段。
具体实现如下:
(1)在oracle数据库中添加log字段,类型为String类型,对应的pojo中Log也需要添加String类型的Log字段的get、set方法。
(2)在LogAsPect.java中,添加代码如下:
//获取主机ip
String ip = getRemoteHost(request);
sys_log.setIp(ip);
log.info("当前登陆人:{},类名:{},方法名:{},参数:{},执行时间:{},ip:{}",username, className, methodName, args, time,ip);
//将log插入数据库中
sysLogService.insertLog(sys_log);
同一java文件中,调用私有的 getRemoteHost函数。
//获取主机ip
private String getRemoteHost(HttpServletRequest request) {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (String s : ips) {
if (!("unknown".equalsIgnoreCase((String) s))) {
ip = s;
break;
}
}
}
return ip;
}
LogMapper.xml中代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tjm.mapper.LogMapper">
<insert id="insertLog" parameterType="SysLog" >
<selectKey keyProperty="log_id" resultType="int" order="BEFORE">
select nvl(max("log_id"),0)+1 from "SysLog"
</selectKey>
insert into "SysLog"("log_id","username","class_name","method_name","args","creat_time","ip")
values(#{log_id},#{username},#{class_name},#{method_name},#{args},#{creat_time},#{ip})
</insert>
</mapper>
(3)修改后的前端代码如下:
<tr class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>日志编号</th>
<th>操作人</th>
<th>操作类名</th>
<th>操作方法名</th>
<th>参数</th>
<th>主机ip</th>
<th>操作时间</th>
</tr>
</thead>
<tbody>
<tr th:each="log:${logs}">
<td th:text="${log.getLog_id()}"></td>
<td th:text="${log.getUsername()}"></td>
<td th:text="${log.getClass_name()}"></td>
<td th:text="${log.getMethod_name()}"></td>
<td th:text="${log.getArgs()}"></td>
<td th:text="${log.getIp()}"></td>
<td th:text="${log.getCreat_time()}"></td>
</th:each>
</tr>
</tbody>
</table>