1.先自定义一个注解:代码如下:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@Documented
public @interface FilterAnnotation {
String desc();//用户接口描述
}
2.写一个aop
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
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.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.xinge.model.OperateLog;
import com.xinge.model.User;
import com.xinge.service.OperateLogService;
@Aspect
@Component
public class OperateLogAop {
@Autowired
OperateLogService operateLogService;
@Before("within(com.xinge.controller..*) && @annotation(filterAnnotation)")
public void getInfo(FilterAnnotation filterAnnotation) throws IOException {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String uri = request.getRequestURI();
//从session获取用户信息
User user = (User) request.getSession().getAttribute("user");
if (user != null) {
OperateLog operateLog= new OperateLog();
operateLog.setCreateTime(new Date());
operateLog.setUsername(user.getUsername());
operateLog.setAction(uri);
operateLog.setIp(getIpAddress(request));
operateLog.setDescription(filterAnnotation.desc());
operateLogService.add(operateLog);
}
}
/**
* 获取ip
* @param request
* @return
* @throws IOException
*/
public final static String getIpAddress(HttpServletRequest request) throws IOException {
// 获取请求主机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 (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
}
3.使用的时候只需在方法上加入注解就行
@FilterAnnotation(desc = "添加用户信息")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public Object add(@User user)