自定义注解 aspectj方式

自定义注解 aspectj方式
spring-servlet.xml

	
    

@IpLoginAnnotation

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface IpLoginAnnotation {
    boolean IpLogin() default true;
}

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

应用


	@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")
	}

你可能感兴趣的:(java)