springboot之使用aop同意处理web请求十七

1、加入aop的依赖:

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

2、定义一个aop的切面,详细aop的调用请看Aop的调用方式

此处是拦截controller包下所有的方法

package com.mybatis.aop;

import com.mybatis.controller.helloController;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;


@Aspect       //定义一个切面
@Component     //注入到spring容器中
public class WebLogAspect {
    private static org.slf4j.Logger log = LoggerFactory.getLogger(helloController.class);

    @Pointcut("execution(public * com.mybatis.controller.*.*(..))")      //定义一个切入点,表示从哪里开始拦截
    public void webLog(){
        log.info("--------------*****--------------***********---------------");
    }
    @Before("webLog()")    //请求之后开始拦截
    public void doBefore() throws Throwable{
        //接收到请求,记录请求内容
        ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        log.info("-----------------------请求开始-----------------------");
        log.info("URL:"+request.getRequestURL().toString());
        log.info("HTTP_METHOD:"+request.getMethod());
        log.info("IP:"+request.getRemoteAddr());
        //记录下请求内容
        Enumeration<String> enu=request.getParameterNames();
        log.info("----------:"+enu.toString());
        log.info("----------:"+enu.hasMoreElements());

        while(enu.hasMoreElements()){
            String name=(String)enu.nextElement();
            log.info("name:{"+name+"},value:{"+request.getParameter(name)+"}");
        }
    }

   @AfterReturning(returning = "ret",pointcut="webLog()")
    public void doAfterReturning(Object ret) throws Throwable{
        //处理完请求,返回内容
        log.info("RESPONSE:"+ret);
        log.info("-----------------------请求结束-----------------------");
    }
}

3、运行*Application类:

在页面调用任意controller下一个方法,运行结果如下:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值