spring知识六------AOP五大通知
https://blog.csdn.net/sinat_28978689/article/details/62215513
本文采用的是@Around,即环绕通知。直接上代码吧。
1、创建注解类:SystemLog
package com.system.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {
/** 要执行的操作类型比如:用户add操作 **/
String module() default "";
}
2、新建类一个切面类:SystemLogAspect
package com.system.annotation;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.system.po.DcLog;
import com.system.po.Userlogin;
import com.system.service.LogService;
import com.system.util.IPUtil;
@Aspect
@Component
public class SystemLogAspect {
@Autowired
private LogService logService;
DcLog log = new DcLog();
@Around("within(com.system.controller..*) && @annotation(archivesLog)")
public Object around(ProceedingJoinPoint pjd, SystemLog systemLog) throws Throwable {
try {
//日志实体对象
System.out.println("进入方法!");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//log.setLogId(null);
log.setCtime(new Date());
long startTime=System.currentTimeMillis();
//类名
String className = pjd.getTarget().getClass().getName();
log.setClasz(className);
//方法名
String methodName = pjd.getSignature().getName();
log.setMethod(methodName);
//获取请求参数
Object[] params = pjd.getArgs();
String paramsStr = "";
for(Object param:params) {
paramsStr += (param + ",");
}
log.setParams(paramsStr);
//请求地址
String uri = request.getRequestURI();
log.setUri(uri);
System.out.println("uri="+uri);
//IP
String host = IPUtil.getIp(request);
log.setHost(host);
//--上面代码为方法执行前--
//--下面代码为方法执行后--
String message = systemLog.module();
log.setMessage(message);
System.out.println("message="+message);
//操作人
/*HttpSession session = request.getSession();
Userlogin thisUser = (Userlogin) session.getAttribute("loginName");
if (thisUser != null){
int userId = thisUser.getUserid();
log.setUserId(userId);
}
System.out.println("thisUser="+thisUser);*/
//结束时间
long endTime=System.currentTimeMillis();
float excTime=(float)(endTime-startTime)/1000;
log.setEndtime(new Date());
log.setExctime(excTime);
System.out.println("log="+log);
//录入数据库
// 日志的service层和dao 可以通过逆向工程生成代码,注入,再调用保存到数据库。
logService.insertSelective(log);
} catch (Exception e) {
e.printStackTrace();
}
//执行方法,获取返回参数
Object result = pjd.proceed();
return result;
}
}
3、获取IP的工具类 IPUtil:
package com.system.util;
import java.net.InetAddress;
import javax.servlet.http.HttpServletRequest;
public class IPUtil {
public static String getIp(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.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();
//System.out.println("访问ip="+ip);
if(ip.equals("127.0.0.1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
ip= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ip!=null && ip.length()>15){ //"***.***.***.***".length() = 15
if(ip.indexOf(",")>0){
ip = ip.substring(0,ip.indexOf(","));
}
}
//System.out.println("访问ip========="+ip);
return ip;
}
}
4、修改springMVC配置文件
其次需要添加如下标签:
<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="systemLogAspect" class="com.system.annotation.SystemLogAspect"></bean>
此处需要注意, proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么就是使用JDK实现动态代理。
5、附上日志实体类
package com.system.po;
import java.io.Serializable;
import java.util.Date;
public class DcLog implements Serializable {
private Integer logId;
private Date ctime;
private Date endtime;
private Float exctime;
private String host;
private String clasz;
private String method;
private String params;
private String message;
private String uri;
private Integer userId;
省略get和set方法
}
新建表的SQL语句:
CREATE TABLE `dc_log` (
`log_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`ctime` datetime DEFAULT NULL COMMENT '生成时间',
`endtime` datetime DEFAULT NULL COMMENT '结束时间',
`exctime` float(11,0) DEFAULT NULL COMMENT '执行时间(秒)',
`host` varchar(45) DEFAULT NULL COMMENT '主机',
`clasz` varchar(45) DEFAULT NULL COMMENT '类名',
`method` varchar(45) DEFAULT NULL COMMENT '方法名',
`params` varchar(500) DEFAULT NULL COMMENT '参数',
`message` varchar(255) DEFAULT NULL COMMENT '消息',
`uri` varchar(255) DEFAULT NULL COMMENT '请求地址',
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='系统日志';