SpringBoot2.0学习之使用Aop技术处理web请求信息

SpringBoot2.0学习之使用Aop技术处理web请求信息

1. 在pom.xml中引入aop的依赖

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

2. 创建切面

@Aspect
@Component
public class WebLogAspect {
	// 获取log对象,将请求信息放入日志中
    private Logger log =  LoggerFactory.getLogger(WebLogAspect.class);
}
@Aspect注解用来将类定义为切面。

3. 创建切点

@Pointcut("execution(public * com.qf.demo.controller..*.*(..))")
public void weblog(){}
@Pointcut注解用来定义切点,括号内为切入规则。

4. 拦截请求信息只需要用到Aop的前置通知和后置通知即可,如下:

// 前置通知 : 拿到请求后,获取请求信息和参数信息
    @Before("weblog()")
    public void doBefore(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("url    : " + request.getRequestURL().toString());
        log.info("method : " + request.getMethod());
        log.info("ip     : " + request.getRemoteAddr());
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            log.info("key:{},value:{}", name, request.getParameter(name));
        }
    }
    
    // 后置通知: 获取返回的结果
    @AfterReturning(returning = "response", pointcut = "weblog()")
    public void doAfterReturning(Object response) {
        log.info("response : " + response);
    }
前置通知 :拿到请求后,获取请求信息和参数信息。
后置通知: 获取返回的结果。

5. 测试结果:

在这里插入图片描述


当你觉得自己不行的时候,

就去走斑马线,

这时候,你就是个行人。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值