前言
面向切面(AOP)Aspect Oriented Programming是一种编程范式,与语言无关,是一种程序设计思想,它也是spring的两大核心之一。
在spring Boot中,如何用AOP实现拦截器呢?
首先加入依赖关系:
?
1
2
3
4
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
|
希望截拦如下Controller:
?
1
2
3
4
5
6
7
8
9
10
|
@RestController
public class MyController {
@RequestMapping (value= "/hello" , method=RequestMethod.GET)
public String hello() {
return "" ;
}
}
|
首先要创建一个拦截类:RequestInterceptor
并且使用@Aspect和@Component标注这个类:
?
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
|
@Component
@Aspect
public class RequestInterceptor {
@Pointcut ( "execution(* com.example.controller.*.*(..))" )
public void pointcut1() {}
@Before ( "pointcut1()" )
public void doBefore() {
System.out.println( "before" );
}
@Around ( "pointcut1()" )
public void around(ProceedingJoinPoint thisJoinPoint) throws Throwable {
System.out.println( "around1" );
thisJoinPoint.proceed();
System.out.println( "around2" );
}
@After ( "pointcut1()" )
public void after(JoinPoint joinPoint) {
System.out.println( "after" );
}
@AfterReturning ( "pointcut1()" )
public void afterReturning(JoinPoint joinPoint) {
System.out.println( "afterReturning" );
}
@AfterThrowing ( "pointcut1()" )
public void afterThrowing(JoinPoint joinPoint) {
System.out.println( "afterThrowing" );
}
}
|
只需要使用@Before,@After等注解就非常轻松的实现截拦功能。
这里需要处理请求,所以我们需要在拦截器中获取请求。
只需要在方法体中使用:
?
1
2
|
ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
|
就可以获取到request。
同理也可以在After等方法中获取response。
获取request之后,就可以通过request获取url,ip等信息。
如果我们想要获取当前正在拦截的方法的信息。可以使用JoinPoint。
例如:
?
1
2
3
4
5
|
@After ( "pointcut1()" )
public void after(JoinPoint joinPoint) {
logger.info( "CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName());
System.out.println( "after" );
}
|
就可以获取包名,类名,方法名。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持。
原文链接:http://blog.csdn.net/a60782885/article/details/68489520
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 46
-
2025-05-24 55
-
2025-05-29 77
-
2025-06-04 23
-
2025-06-05 78
热门评论