aop

 

 

 

过滤器:
获取参数

interceptor拦截器:
获取注解
获取请求数据,拦截
拿到类、方法、参数对象类型

切面:
获取注解
请求及响应数据,获取和操作
拿到类、方法、参数(参数对象)

 

        @Aspect
	@Component
	@Order(1)
	public class AopTest {
		private static final Logger logger = LoggerFactory.getLogger(AopTest.class);
		@Pointcut("@annotation(aopTestAnnotation)")
		public void annotationPointcut(AopTestAnnotation aopTestAnnotation) {
		}

		@Around("annotationPointcut(aopTestAnnotation)")
		public Object aroundPointcut(ProceedingJoinPoint joinPoint, AopTestAnnotation aopTestAnnotation) throws Throwable {
			logger.info("**************AopTest.before");
			Object[] args = joinPoint.getArgs();
			for (Object arg : args) {
				logger.info("**************AopTest参数="+arg+" ");
				ESBRenewRewardRequestVO vo = (ESBRenewRewardRequestVO)arg;
				vo.setPolicyNo("9200200012343");//修改入参
			}

            //第二种参数获取方式
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = servletRequestAttributes.getRequest();
			logger.info("**************AopTest.request:"+request.getParameter("userId"));//request无法对参数修改

			logger.info("**************AopTest.annotation:"+aopTestAnnotation.value());
		   //第二种获取注解值的方式
			logger.info("**************AopTest.annotation.切入方法名:"+joinPoint.getSignature().getName()+",切入类名:"+joinPoint.getSignature().getDeclaringTypeName());
			MethodSignature ms= (MethodSignature)joinPoint.getSignature();
			AopTestAnnotation smaAnnotation = ms.getMethod().getAnnotation(AopTestAnnotation.class);
			if(smaAnnotation!=null)
				logger.info("**************AopTest.annotation2:"+smaAnnotation.value()+",签名signature:"+ms+",返回AOP框架为目标对象生成的代理对象getThis同Target:"+joinPoint.getThis());
			//第三种获取注解值的方式
			Object target = joinPoint.getTarget();
			java.lang.reflect.Method method = target.getClass().getMethod(ms.getName(), ms.getParameterTypes());//获取注解标注的方法
			AopTestAnnotation annotation = method.getAnnotation(AopTestAnnotation.class);//通过方法获取注解
			if(annotation!=null)
				logger.info("**************AopTest.annotation3:"+smaAnnotation.value()+",目标对象target:"+target);

			Object obj = joinPoint.proceed();

			ResultVO<ESBRenewRewardInfoVO> resultVO = (ResultVO<ESBRenewRewardInfoVO>)obj;
			resultVO.getData().setOrderNo("10000012323213");//修改出参
			logger.info("**************AopTest.after:"+resultVO);
			return obj;
		}
	}


        @Documented
	@Target({ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface AopTestAnnotation {
		String value() default "";
	}

	@Aspect
	@Component
	@Order(2)//order越大距离目标方法越近
	public class AopTestTwo {
		private static final Logger logger = LoggerFactory.getLogger(AopTestTwo.class);
		@Pointcut("@annotation(AopTestAnnotationTwo)")
		public void annotationPointcut() {
		}
		@Around("annotationPointcut()")
		public Object aroundPointcut(ProceedingJoinPoint joinPoint) throws Throwable {
			logger.info("@@@@@@@@@@@@@@@@@@@AopTestTwo.before");
			Object obj = joinPoint.proceed();
			logger.info("@@@@@@@@@@@@@@@@@@AopTestTwo.after");
			return obj;
		}
		@Before("annotationPointcut()")
		public void aroundPointcutBefore(JoinPoint joinPoint) throws Throwable {
			logger.info("@@@@@@@@@@@@@@@@@@@AopTestTwo.aroundPointcutBefore:"+joinPoint.getArgs());
		}
		// @After("annotationPointcut()")
		@AfterReturning(returning = "obj",pointcut="annotationPointcut()")
		public void aroundPointcutAfter(JoinPoint joinPoint,Object obj) throws Throwable {
			logger.info("@@@@@@@@@@@@@@@@@@@AopTestTwo.aroundPointcutAfter:"+obj);
		}
	}

	@AopTestAnnotation("test000001")
	@AopTestAnnotationTwo
	@RequestMapping(value = "/insuranceSport")
	@ResponseBody
	public ResultVO<ESBRenewRewardInfoVO> test(ESBRenewRewardRequestVO request) {
		logger.info("***************test:"+request);
		ResultVO<ESBRenewRewardInfoVO> result = new ResultVO<ESBRenewRewardInfoVO>();
		ESBRenewRewardInfoVO vo = new ESBRenewRewardInfoVO();
		vo.setOrderNo("123456789");
		result.setData(vo);
		testService.myTest();
		logger.info("***************test:"+result);
		return result;
	}

	@Service
	public class TestService {
		private static final Logger logger = LoggerFactory.getLogger(TestService.class);
		public void myTest(){
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = servletRequestAttributes.getRequest();
			logger.info("**************TestService.myTest:"+request.getParameter("userId"));//request无法对参数修改
		}
	}

  

	@Configuration
	public class MyConfig extends WebMvcConfigurationSupport {
		@Override
		public void addInterceptors(InterceptorRegistry registry) {
			// addPathPatterns("/**") 表示拦截所有的请求,
			// excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
			//.addPathPatterns("/**").excludePathPatterns("/login", "/register");
			registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");///asd/**
		}
	}

	public class MyInterceptor implements HandlerInterceptor {
		//在请求处理之前进行调用(Controller方法调用之前
		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
			System.out.println("preHandle被调用");
			Map map =(Map)request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
			System.out.println(map);

			if (o instanceof HandlerMethod) {
				HandlerMethod handlerMethod = (HandlerMethod) o;
                                //在方法上寻找注解
				AopTestAnnotationTwo permission = (AopTestAnnotationTwo) handlerMethod.getMethodAnnotation(AopTestAnnotationTwo.class);
				if (permission != null) {
                                //获取注解中的值
					String resourceKey = permission.value();
					logger.info("#####################interceptor.注解:" + resourceKey);
				}

				Method method = handlerMethod.getMethod();
				Object action = handlerMethod.getBean();
				logger.info("#####################interceptor:方法名:" +method.getName()+",类名:"+action);

				Class[] paramTypes = method.getParameterTypes();
				Parameter[] methodParameters= method.getParameters();
				logger.info("#####################interceptor:"+methodParameters);
				if (methodParameters.length != 0) {
					Parameter methodParameter = methodParameters[0];
					String parameterName = methodParameter.getName();
					String parameterClass = methodParameter.getType().getCanonicalName();
					String parameterVelue = request.getParameter(parameterName);
					logger.info("#####################interceptor:方法名:" +method.getName()+" "+parameterName+",参数对象类型:"+parameterClass+" "+parameterVelue);
				}
			}

			Map<String, String[]> pars =request.getParameterMap();
			for( Map.Entry<String,String[]> entry: pars.entrySet()){
				String key = (String) entry.getKey();
				String[] value = entry.getValue();
				logger.info("#####################interceptor:"+key+" "+value[0]+" "+ request.getParameter(key));
			}


			if(1==1) {//map.get("name").equals("zhangsan")
				return true;    //如果false,停止流程,api被拦截
			}else {
				PrintWriter printWriter = httpServletResponse.getWriter();
				printWriter.write("please login again!");
				return false;
			}
		}
		@Override
		public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
			System.out.println("postHandle被调用");
		}
		@Override
		public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
			System.out.println("afterCompletion被调用");
		}
	}

	@Target({ ElementType.METHOD, ElementType.TYPE})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface PermissionCheck {
		/**
		 * 资源key
		 * */
		String resourceKey();
	}

	某个接口使用该注解,切面中某些接口的特殊处理
	@PermissionCheck(resourceKey="mykeyss")
	@RequestMapping("/hello")
	@ResponseBody
	public String test( User user) { 

  

	@Bean
	public FilterRegistrationBean indexEsgFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter());
		registration.addUrlPatterns("/*"); //esg.properties别sg.rest.area
		registration.setName("MyFilter");
		registration.setOrder(1);
		return registration;
	}

	public class MyFilter implements Filter {
		private static final Logger logger = Logger.getLogger(MyFilter.class);
		public void init(FilterConfig filterConfig) throws ServletException {
		}
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest)servletRequest;
			Map map = request.getParameterMap();
			String name = request.getParameter("userId");
			String method = request.getMethod();
			String uri = request.getRequestURI();
			logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~MyFilter:"+map+",参数:"+name+",method.get/post:"+method+",uri:"+uri);
			filterChain.doFilter(servletRequest,servletResponse);
		}
		@Override
		public void destroy() {
		}
	}

  

 

上一篇:Reactor响应式编程 记录web访问日志 filter+AOP


下一篇:SpringBoot整合AOP超详细教程