springboot aop获取controller的POST @RequestBody注解参数

项目使用vue+springboot做前后端分离,在做校验的时候需要用到aop拦截

vue

this.$axios.post("http://localhost:8281/store-api/order/test",{
		token:"testtoken"
	}).then(response => {
		console.log(response.data);
	});

vue怎么安装axios自行百度

controller

@CrossOrigin	//为了跨域
@RestController
@RequestMapping("order")
public class OrderApi {
    @Autowired
    OrderService orderService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("test")
    public Object test(@RequestBody JSONObject o){
        logger.info(o.toJSONString());
        return o;
    }
}

我们需要拦截到上面test方法里的o参数

aop

@Aspect
@Configuration
public class CheckAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义切点Pointcut  自行写入对应的controller包路径
    @Pointcut("execution(* com.ls.store_service.controller.*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        //这里可以获取到get请求的参数和其他信息
        logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
        //重点 这里就是获取@RequestBody参数的关键  调试的情况下 可以看到o变量已经获取到了请求的参数
        Object[] o = pjp.getArgs();

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        return result;
    }

}

开启调试模式,vue运行发送一个ajax请求,可以看到已经拦截成功并获取到了@RequestBody的参数

你可能感兴趣的:(前端,Java)