最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
SpringBoot使用Aspect切面拦截打印请求参数代码示例
时间:2022-06-29 02:18:41 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下SpringBoot使用Aspect切面拦截打印请求参数代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
AspectJ作为语言级别的AOP框架,功能相比于SpringAOP更加强大。SpringAOP旨在提供给用户一个轻量级的AOP实现方案,它只能应用在SpringIOC容器中管理的bean。而AspectJ旨在提供给用户一个完整的AOP解决方案,它可以应用在所有的域对象中,下面给大家介绍SpringBoot使用Aspect切面拦截打印请求参数的代码。
引入依赖
org.springframework.boot spring-boot-starter-aop
也用到了fastjson打印参数 , 如果引了就不需要(也可以根据自己的来打印)
com.alibaba
fastjson
1.2.15
LogAspect.java
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
/**
* @author zhipeih
* @date 2021/07/14
*/
@Slf4j
@Component
@Aspect //表示它是一个切面
public class LogAspect {
/**
*
* execution:改成自己要打印的控制器路径
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("execution(* com.example.*.controller.*.*(..)) ")
public Object handleControllerMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//原始的HTTP请求和响应的信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
//获取当前执行的方法
Method targetMethod = methodSignature.getMethod();
//获取参数
Object[] objects = proceedingJoinPoint.getArgs();
//获取返回对象
Object object = proceedingJoinPoint.proceed();
StringBuilder sb = new StringBuilder(1000);
sb.append("-------------------------------------------------------------n");
sb.append("Controller: ").append(targetMethod.getDeclaringClass().getName()).append("n");
sb.append("Method : ").append(targetMethod.getName()).append("n");
sb.append("Params : ").append(JSON.toJSONString(objects)).append("n");
sb.append("URI : ").append(request.getRequestURI()).append("n");
sb.append("URL : ").append(request.getRequestURL()).append("n");
sb.append("Return : ").append(object).append("n");
sb.append("-------------------------------------------------------------n");
System.out.println(sb);
return proceedingJoinPoint.proceed();
}
}
相关文章
- 2925邮箱官方入口直达-2925邮箱官网一键访问入口 12-19
- 雨课堂在线登录入口-雨课堂网页版在线学习平台 12-19
- dnf神界梦境幻象触发条件攻略 梦境幻象怎么触发 12-19
- dnf迷雾注视度有什么用 迷雾注视度100%效果介绍 12-19
- jk漫画天堂-禁漫成人秘密入口 jk漫画天堂-私密隐藏网站 12-19
- dnf神界地图奖励及名望要求大全 12-19