spring aop 中使用@Aspect扫描注解用作(权限或特殊处理)

jar包:

 
            org.aspectj
            aspectjrt
            1.7.4
        
        
            org.aspectj
            aspectjweaver
            1.7.4
        
        
            cglib
            cglib
            3.1
        
                
            javax.servlet
            jstl
            1.2
            jar
        
        
            javax.servlet
            javax.servlet-api
               3.0.1
            provided
        
        
            javax.servlet.jsp
            jsp-api
            2.2
            provided
        

spring-mvc.xml


     
    

control demo:

package demo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class DemoInterceptor {

	static Integer count = 0;

	// 切入点要拦截的类 声明一个切入点,切入点的名称其实是一个方法
	@Pointcut("@annotation(注解的全路径.注解类A) || @annotation(注解的全路径.注解类B)")
	private void anyMethod() {
	}

	// 环绕通知(拦截)
	@Around("anyMethod()")
	public Object trackInfo(ProceedingJoinPoint jp) throws Throwable {
		Signature signature = jp.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method targetMethod = methodSignature.getMethod();
		// 对于有注解的方法进行权限验证
		boolean b = targetMethod.isAnnotationPresent(注解类A.class);
		boolean c = targetMethod.isAnnotationPresent(注解类B.class);
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		if (b) {// 带有注解类A拦截
			注解类A a= targetMethod.getAnnotation(注解类A.class);
			//a. 获取参数
            //业务处理
		}
		if (c) {// 带有注解类B拦截
			注解类B b= targetMethod.getAnnotation(注解类B.class);
			//b. 获取参数 
            //业务处理
		}
		Object object = jp.proceed();
		return object;
	}
}

 

你可能感兴趣的:(java,web,spring,aop,aop,Aspect)