Details of Spring Boot processing requests

  • 2020-10-23 20:07:11
  • OfStack

preface

Aspect Oriented Programming is a programming paradigm, language-independent, and a programming idea. It is also one of the two core elements of spring.

In spring Boot, how do you implement interceptors with AOP?

First add dependencies:


<dependency> 
 <groupId>org.springframework.boot</groupId> 
 <artifactId>spring-boot-starter-aop</artifactId> 
</dependency> 

Wish to intercept Controller as follows:


@RestController 
public class MyController { 
 
  
 @RequestMapping(value="/hello", method=RequestMethod.GET) 
 public String hello() { 
  return ""; 
 } 
  
} 

The first step is to create an interception class: RequestInterceptor

And annotate this class with @Aspect and @Component:


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

Just using @Before, @ES32en and other annotations makes intercepting very easy.

We need to process the request here, so we need to get the request in the interceptor.

You only need to use it in the method body:


ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
HttpServletRequest request = attributes.getRequest(); 

You get request.

Similarly, response can be obtained in methods such as After.

After acquiring request, you can obtain url, ip and other information through request.

If we want to get information about the method we are currently intercepting. You can use JoinPoint.

Such as:


@After("pointcut1()") 
public void after(JoinPoint joinPoint) { 
 logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName()); 
 System.out.println("after"); 
} 

You can get the package name, class name, method name.

conclusion


Related articles: