Moment For Technology

Spring-AOP and AOP to obtain the request parameters operation

Posted on Dec. 3, 2022, 7:55 a.m. by Bradley Jackson
Category: The back-end Tag: The back-end spring

Spring-aop and AOP obtain the parameters of the request

AOP, called aspect oriented programming, is mainly used to solve some system level problems in program development, such as logging, transactions, permissions and so on.

Basic concepts of AOP

  • Aspect (cut): is usually a class where pointcuts and advice can be defined
  • JointPoint(join point): an explicit point in the execution of a program, usually a method call
  • Advice (notice): the AOP on specific point execution enhancement processing, have before, after, afterReturning, afterThrowing, around
  • PointcutA: is a join point with advice, which occurs in programs primarily by writing pointcut expressions
  • AOP agent: An object created by an AOP framework, the proxy is an enhancement of the target object. AOP proxies in Spring can be EITHER JDK dynamic proxies, interface-based, or CGLIB proxies, subclass-based

Second, the Spring AOP

Spring uses THE JDK dynamic proxy by default. Spring automatically switches to the CGLIB proxy when it needs a proxy class rather than a proxy interface. However, the current projects are interface oriented programming, so the JDK dynamic proxy is used relatively more.

Third, annotation-based AOP configuration

1. Enable @asjectj support

Configure the following sentence in the Spring configuration:

aop:aspectj-autoproxy /
Copy the code

Or use a comment:

Copy the code

2. Description of notification types

(1) Before: Do enhancement Before the target method is called, @before only needs to specify the pointcut expression

AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning: AfterReturning

(3) AfterThrowing: This is used for handling unhandled exceptions in the program. @Afterthrowing can also specify a parameter name for the return value of the entry point expression. This parameter name can be used for AfterThrowing

To access the exception object thrown by the target method

(4) After: Do the enhancement After the target method has completed, regardless of whether the target method has completed successfully. @after can specify a pointcut expression

(5) Around: The process is enhanced before and after the completion of the target method. Around is the most important type of notification. For example, transactions, logs, and the like, there is a ProceedingJoinPoint

3. Priority of notification execution

To enter the target method, start with Around and then Before. To exit with AfterReturning, start with Around and then After.

Note :Spring AOP's wrap notifications affect AfterThrowing notifications. Do not use them together! It doesn't make sense to use it at the same time.

4. Pointcut definitions and expressions

The definition of pointcut expressions is the core of AOP as a whole and has its own specification

Spring AOP supports pointcut indicators:

Execution: Used to match the join point of the execution method

A: the @pointcut (" execution (* com. Aijava. Springcode. Service... . (...). ) ")Copy the code

The first one matches any method return value,... (Two dots) indicates zero or more, the first above... Represents the service package and its subpackages, the second represents all classes, the third * represents all methods, the second... said

Number of arbitrary arguments to a method

B: the @pointcut (" within (com) aijava. Springcode. Service. *) ")Copy the code

Within specifies the join point of a matching method. The above is any join point that represents a matching service package

C: the @pointcut ("this(com. Aijava. Springcode. Service. UserService) ").Copy the code

This is used to qualify that an AOP proxy must be an instance of a specified type, as above, specifying a specific instance, which is UserService

D: the @pointcut (" bean (userService) ")Copy the code

Beans, which specify the name of the bean in the IOC container, are also very common

The following is a log method that uses AOP to obtain the execution time of the statistical calculation method and obtain the request parameters, etc.

/** * description: * count request execution time ** @author wkGui */
public class ResExeTimeCounter {
    private static Logger logger = LoggerFactory.getLogger(ResExeTimeCounter.class);
    @Pointcut("execution(* com.wk.controller.. *. * (..) )")
    public void pointCut(a) {
    public Object around(ProceedingJoinPoint pjp) throws Throwable { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; assert sra ! = null; HttpServletRequest request = sra.getRequest(); String url = request.getRequestURL().toString(); String method = request.getMethod(); String queryString = request.getQueryString();long startTime = System.currentTimeMillis();"{url:{}, method:{}, queryString:{}}", url, method, queryString);
        Object rs;
        boolean successAble = false;
        JsonObject paramsJson = new JsonObject();
        try {
            Object[] params = pjp.getArgs();
            for (int i = 0; i  params.length; i++) {
                if (params[i] instanceof BindingResult
                        || params[i] instanceof HttpRequest
                        || params[i] instanceof HttpResponse){
                paramsJson.addProperty("param-" + i, JsonUtil.toJsonWtihNullField(params[i]));
            rs = pjp.proceed();
            successAble = true;
        } finally {
  "{url:{}, method:{}, success-able:{}, exe-time:{}, params:{}}", url, method, successAble, System.currentTimeMillis() - startTime, paramsJson);
        returnrs; }}Copy the code

SpringAOP obtains all parameters in the request and records user operation logs

Today made an AOP management log, egg pain very....

Stick to the code as usual

First, you need these three packages in addition to the AOP package.


So if you want to go into Controllers, write this code into your MVC configuration, and that's why you've been trying to do it all morning.

Method is the name of the method that you enter into the class

You can make a template of this, PS: Ignore the notes ha, obsessive compulsive disorder

Because I'm only going to have two parameters in my control class request and response, so I'm just going to have request equals zero,

The following

  Enumeration parameter = request.getParameterNames();
  while(parameter.hasMoreElements()) {
  String a=(String) parameter.nextElement();
Copy the code

Request.getparameter (a), parameter name :a

The above code can be tested with AOP, but if it is put in an interceptor, the test will return a date, and for some reason it will occasionally work with get requests. Post must be abnormal, no problem with AOP

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.