七 aop处理请求
1.内容
aop 是 编程范式,与语言无关,是编程设计思想
2.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
在com.boot下新建aspect包
package com.boot.aspect;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
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.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.boot.web.StuController.*(..))") //Pointcut切点, *表示所有 , ..表示该方法下的所有
public void log(){
}
@Before("log()")//Before方法执行之前
public void doBefore(JoinPoint joinpoint){
//url
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("url={}",request.getRequestURI());
//method
logger.info("method={}",request.getMethod());
//ip
logger.info("ip={}",request.getRemoteAddr());
//类方法
logger.info("class_method={}",joinpoint.getSignature().getDeclaringTypeName()+"."+joinpoint.getSignature().getName());
//参数
logger.info("args={}",joinpoint.getArgs());
}
@After("log()")//@After方法执行之后
public void doAfter(){
logger.info("22222222");
}
@AfterReturning(returning = "object",pointcut = "log()")//记录返回值
public void doAfterReturning(Object object){
logger.info("response={}",object.toString());
}
}
注意,日志的包导入的是org.slf4j ,底层实现使用的是logback
在Stu类中添加方法
@Override
public String toString() {
return "Stu [id=" + id + ", name=" + name + ", age=" + age + "]";
}