https://blog.csdn.net/weixin_39549656/article/details/83341427
自定义注解 aspectj方式
spring-servlet.xml
<!-- aop 注解实现 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 1
- 2
@IpLoginAnnotation
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface IpLoginAnnotation {
boolean IpLogin() default true;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
LogAspect.class
package com.ccd.util.annotation.iplog;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect //该注解标示该类为切面类
@Component //注入依赖
public class LogAspect {
//标注该方法体为后置通知,当目标方法执行成功后执行该方法体
@Before(value = " @annotation(rl)")
public void addLogSuccess(JoinPoint jp, IpLoginAnnotation rl){
HttpServletRequest request = null;
System.out.println("进入");
Object[] parames = jp.getArgs();//获取目标方法体参数
for (int i = 0; i < parames.length; i++) {
System.out.println(parames[i]);
Object object = parames[i];
if(object instanceof HttpServletRequest){
request=(HttpServletRequest)object;
String ip = request.getRemoteAddr();// 返回发出请求的IP地址
System.out.println("ip地址 :"+ip);
}
}
Signature pojo = jp.getSignature();
System.out.println(pojo);//String com.ccd.user.action.UserAction.insert(User,String)
System.out.println(pojo.getName()); //insert
String className = jp.getTarget().getClass().toString();//获取目标类名
System.out.println("className:" + className);
className = className.substring(className.indexOf("com")); //className:class com.ccd.user.action.UserAction
String signature = pojo.toString();//获取目标方法签名
System.out.println("signature:" + signature);//signature:String com.ccd.user.action.UserAction.insert(HttpServletRequest,HttpServletResponse,User,String)
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
应用
@IpLoginAnnotation
@RequestMapping("/insert")
// 新增-保存数据方法
public String insert(HttpServletRequest request, HttpServletResponse response,User user,String name) {
System.out.println("获得name :"+name);
service.insert(user);
return "redirect:list";
// 重定向到本类的@RequestMapping("list")
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
</div>