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)?