- 在web.xml中配置一个监听器,可以通过该监听器获得访问者的ip

- 日志记录的java代码
package cn.lld.controller;
import cn.lld.domain.SysLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
@Component
@Aspect
public class LogAop {
@Autowired
private HttpServletRequest request;
private Date visitTime;
private String username;
private String ip;
private String url;
private Long executionTime;
private Method method;
private Class clazz;
@Before("execution(* cn.lld.controller.*.*(..))")
public void doBefore(JoinPoint joinPoint)throws NoSuchMethodException{
visitTime = new Date();
clazz = joinPoint.getTarget().getClass();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
if (args == null || args.length == 0){
method = clazz.getMethod(methodName);
}else {
Class[] classArgs = new Class[args.length];
for (int i = 0; i < args.length; i++) {
classArgs[i] = args[i].getClass();
}
method = clazz.getMethod(methodName, classArgs);
}
}
@After("execution(* cn.lld.controller.*.*(..))")
public void doAfter(JoinPoint jp) throws Exception {
executionTime = new Date().getTime() - visitTime.getTime();
if (clazz != null && method != null && clazz != LogAop.class) {
RequestMapping classAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
if (classAnnotation != null) {
String[] classValue = classAnnotation.value();
RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
if (methodAnnotation != null) {
String[] methodValue = methodAnnotation.value();
url = classValue[0] + methodValue[0];
ip = request.getRemoteAddr();
}
}
}
SysLog sysLog = new SysLog();
sysLog.setExecutionTime(executionTime);
sysLog.setIp(ip);
sysLog.setMethod("[类名] " + clazz.getName() + "[方法名] " + method.getName());
sysLog.setUrl(url);
sysLog.setUsername(username);
sysLog.setVisitTime(visitTime);
}
}