springboot使用注解方式aop,获取注解参数,处理request和response
springboot aop使用注解,获取注解参数,处理request和response
这里实现一个简单的登陆判断注解
加了LonginAction的方法必须登陆才能执行
1
首先检查是否导入相关springboot aop启动器依赖
org.springframework.boot spring-boot-starter-aop 2.1.1.RELEASE
2 创建切点注解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface LoginAction { String value() default "";}
2 创建切面类
这里只作web访问时的简单演示
@Component@Aspectpublic class UserAspect {//配置切点 @Pointcut("@annotation(com.ji.LoginAction)") public void LoginAction(){}; @Around("LoginAction()") public Object toLogin(ProceedingJoinPoint pjp) throws Throwable { //获取request和response ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); HttpServletResponse response = attributes.getResponse(); String requestURI = request.getRequestURI(); MethodSignature signature = (MethodSignature) pjp.getSignature(); LoginAction annotation = signature.getMethod().getAnnotation(LoginAction.class); if (annotation.needLogin()){ //这里可以对需要登陆的接口进行是否登陆的判断,具体操作这里省略,这里默认没有登陆,根据项目来进行编写,也可以加入其他注解参数// request.getSession().getAttribute("userId"); response.sendRedirect("/login.html"); System.out.println("该接口需要登陆");// throw new RuntimeException("该接口需要登陆"); return null; }else { System.out.println("该接口不需要登陆"); //执行controller方法,o为该方法的返回值,也可以对返回值进行处理 Object o = pjp.proceed(); System.out.println("接口访问成功"); //这里测试对String类型处理 o+="-----deal------"; return o; } }}
使用@Around环绕能阻止controller方法执行,@Before也能阻止方法执行,只不过需要手动抛出异常来进行阻止
还要说明一点,这里自定义注解只加了一个needLogin参数,可以结合具体项目加入更多参数来进行判断,获取参数值方法同needLogin值的获取
3 创建测试controller
@RequestMapping("test") @LoginAction(needLogin = false) public String test(String name){ System.out.println("controller"); return "success!!! "+"欢迎"+name; } @RequestMapping("test1") @LoginAction(needLogin = true) public String test1(){ System.out.println("需要登陆的接口"); return null; } @RequestMapping("test2") public String test2(){ System.out.println("没有添加注解的登陆的接口"); return null; }
3 进行测试
1 (test)有LoginAction注解并且value值为false
可以看出来在Around方法里对返回值进行了处理
控制台信息
2 (test1)有LoginAction注解并且value值为true
这里访问被后台判断跳转到登陆页面,没有执行controller方法
控制台信息
2 (test2)没有LoginAction注解
没有加LoginAction注解的正常访问