springboot的切面aop

  在springboot项目中使用的切面aop,打印各个请求的请求参数和相应参数。

注意:post请求和get请求获取参数的方式不同。request.getQueryString();使用与get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
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.Map;
//描述切面类
@Aspect
@Configuration
@Component
public class HttpControllerAop {
private static final Logger logger = LoggerFactory.getLogger(HttpControllerAop.class);
/**
* 定义切点Pointcut
*/
@Pointcut("execution(* com.hfy..*HttpController.*(..))")
public void excudeService() {
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
Map<String, String[]> params = request.getParameterMap();
if (params != null) {
queryString = mapper.writeValueAsString(params);
}
String method = request.getMethod();
if ("POST".equals(method)) {
Object[] paramsArray = pjp.getArgs();
if (paramsArray.length > 0) {
queryString = mapper.writeValueAsString(paramsArray[0]);
}
} else {
queryString = request.getQueryString();
}
logger.info("请求uri: ({}), params: {}", uri, queryString);
// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
// 过滤 高频或数据量大的日志,不打印
return result;
}
}

文章目录
|