Aop做拦截器 获取请求头数据 修改请求数据拦截返回值修改返回值数据

AOP 拦截器拦截请求头 修改请求参数

请求数据拦截

本页面 按住 ctrl 和 F 搜索
@Before(“doPointcut()”)

返回值数据拦截

本页面 按住 ctrl 和 F 搜索
@AfterReturning(returning = “rvt”,pointcut = “doPointcut()”)

需求解释

每一次请求参数 AOP 拦截 获取请求头某个数据,并且将数据填充到参数中

准备

1.目录结构

在这里插入图片描述

2总结

aop做拦截不是很灵活,不如拦截器灵活,但是某些场景是必须要用到aop的
这个拦截是将请求头中的登录信息拿出来封装到对象中
主要代码就是所有bean继承CommonPojo类
aop会操作CommonPojo 类来复制userId

3.代码

注意事项

Aop做拦截器 获取请求头数据 修改请求数据拦截返回值修改返回值数据_第1张图片

TestAspect

package yu.com.test2.apo;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import yu.com.test2.Result;
import yu.com.test2.TestPojo;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname TestAspect
 * @Date 2021/4/6 15:43
 * @Created by yufx
 */

@Aspect // FOR AOP
@Order(-99) // 控制多个Aspect的执行顺序,越小越先执行
@Configuration // 配置类
public class TestAspect {
/*
            setter方法
            o:要操作类的对象
            args:属性名
            attributeValue:属性值
         */
    public static void setXxx(Object o, String args, Object attributeValue) {
        Class cls = o.getClass();
        //判断该属性是否存在
        Field field = null;
        try {
            field = cls.getDeclaredField(args);
            if (field == null) {
                field = cls.getField(args);
            }
            if (field == null) {
                return;
            }
        } catch (NoSuchFieldException e) {
            e.getMessage();
        }

        String fieldName = "set" + args.substring(0, 1).toUpperCase() + (args.length() > 1 ? args.substring(1) : "");
        Method method = null;
        try {
            method = cls.getMethod(fieldName, attributeValue.getClass());
            method.invoke(o, attributeValue);
        } catch (NoSuchMethodException e) {
            e.getMessage();
        } catch (IllegalAccessException e) {
            e.getMessage();
        } catch (InvocationTargetException e) {
            e.getMessage();
        }
    }

    @Pointcut( "execution( * yu.com.test2..*.*(..))")
    /**
     * 这个方法的方法名要和下面注解方法名一致
     */
    public void doPointcut(){
    }

    @Before("doPointcut()")
    public void doBefore(JoinPoint joinPoint) throws IntrospectionException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // 请求开始时间
        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String headValue  = sra.getRequest().getHeader("userId");

        LOG.info(headValue);
        if (headValue != null && !"".equals(headValue)) {
            //获取目标方法的参数信息
            Object[] obj = joinPoint.getArgs();
            for (Object argItem : obj) {
                if (argItem instanceof Object) {
                    setXxx(argItem, "userId", headValue);
                }
            }
        } else {
            LOG.info("userId 无数据 请联系管理员");
        }
    }

    @After("doPointcut()")
    public void doAfter(){
        System.out.println("==doAfter==");
    }

    /**
     * 返回值拦截修改 controller返回的对象属性不可以修改
     * 只能修改对象里的值属性
     * @param rvt
     * @return
     */
    @AfterReturning(returning = "rvt",pointcut = "doPointcut()")
    public Object AfterExec(Object rvt){
        System.out.println(rvt+"========================");
        Result result1 = (Result) rvt;
        result1.setMsg("123645");
        result1.setSuccess(true);
        return rvt;
    }

    /**
     * 环绕通知返回值类型Object,对应所有被拦截方法的返回值类型,不能为void
     */
    @Around("doPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        System.out.println("==doAround.before==");
        Object ret=proceedingJoinPoint.proceed();
        System.out.println("==doAround.after=="+ret);
        return ret;
    }
}


TestAspect

package yu.com.test2;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 封装返回结果
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class  Result implements Serializable{
    private boolean success;//执行结果,true为执行成功 false为执行失败
    private String msg;//返回结果信息,主要用于页面提示信息
    private Object data;//返回数据

    public static Result okData(Object data) {
        Result result = new Result();
        result.data = data;
        return result;
    }

    public static Result okDataMsg(Object data , String msg) {
        Result result = new Result();
        result.data = data;
        result.msg = msg;
        return result;
    }

    public static Result okDataMsgSuccess(Object data, String msg ,boolean success) {
        Result result = new Result();
        result.data = data;
        result.msg = msg;
        result.success = success;
        return result;
    }

}

TestController

package yu.com.test2;

import org.springframework.web.bind.annotation.*;

/**
 * @Classname TestController
 * @Date 2021/4/6 15:47
 * @Created by yufx
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @PostMapping("/show")
    public String show(@RequestBody TestPojo testPojo) {
        System.out.println("show2----------------------------------"+testPojo);
        return "OK";
    }

    @PostMapping("/show2")
    public String show2(@RequestBody TestPojo testPojo) {
        System.out.println("show2----------------------------------"+testPojo);
        return "OK2";
    }
}

CommonPojo

package yu.com.test2;

import lombok.Data;

/**
 * @Classname CommonPojo
 * @Date 2021/4/8 16:59
 * @Created by yufx
 */
@Data
public class CommonPojo {

    private String userId;
}

TestPojo

package yu.com.test2;

import lombok.Data;
import lombok.ToString;

/**
 * @Classname TestPojo
 * @Date 2021/4/6 16:54
 * @Created by yufx
 */
@Data
@ToString
public class TestPojo  extends CommonPojo{

    private String name;

}
ate 2021/4/6 16:54
 * @Created by yufx
 */
@Data
@ToString
public class TestPojo {

    private String name;
    private String userId;

}

你可能感兴趣的:(java,java)