6.addInterceptors添加拦截器
registry.addInterceptor(BeanKit.getOfType(DebugInterceptor.class));
实现debug拦截器
@Slf4j
@Aspect
@Component
public class DebugInterceptor extends HandlerInterceptorAdapter {
private ThreadLocal<Long> startTime = ThreadLocal.withInitial(System::nanoTime);
private ThreadLocal<Signature> signature = ThreadLocal.withInitial(() -> null);
private ThreadLocal<Object[]> paramsCache = ThreadLocal.withInitial(() -> null);
private ThreadLocal<Object> resultCache = ThreadLocal.withInitial(() -> null);
@Pointcut("execution(public * zool.firefly.controller.*.*(..))")
public void resultAop() {}
@Around("resultAop()")
@SneakyThrows
public Object resultAround(ProceedingJoinPoint pjp) {
val result = pjp.proceed();
resultCache.set(result);
return result;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
startTime.set(System.nanoTime());
paramsCache.set(new Object[]{request.getParameterMap()});
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
StringBuilder str = new StringBuilder();
str.append("\n===================== DebugInterceptor =====================");
str.append("\nRemote IP : ").append(WebKit.getClientIP());
str.append("\nRequest Method : ").append(request.getMethod());
str.append("\nRequest URL : ")
.append(request.getRequestURI())
.append(StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString());
str.append("\nAction Signature : ").append(Optional.ofNullable(signature.get()).map(Object::toString).orElse("Empty"));
str.append("\nRequest Params : ");
Object[] param = paramsCache.get();
if (param != null && param.length == 1 && param[0] instanceof Map) {
str.append(JSON.toJSONString(param[0]));
} else {
Object[] params = Optional.ofNullable(paramsCache.get()).orElse(new Object[]{});
for (int i = 0; i < params.length; i++) {
Object obj = params[i];
// 需要保证类直接继承Object 并且没有实现任何接口 才能用JSON序列化
boolean isPlanObject = Optional
.ofNullable(obj)
.map(o -> o.getClass().getSuperclass().equals(Object.class)
&& !o.getClass().isArray()
&& o.getClass().getInterfaces().length == 0).orElse(true);
str.append(i == 0 ? "[" : "\n [")
.append(i)
.append("] => ")
.append(isPlanObject ? JSON.toJSONString(obj) : String.valueOf(obj));
}
}
str.append("\nResponse Status : ").append(response.getStatus());
//TODO 添加返回结果
str.append("\nHandle Time : ").append(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime.get())).append("ms");
str.append("\n============================================================");
log.info(str.toString());
signature.remove();
paramsCache.remove();
resultCache.remove();
}
}
访问时的效果:
自定义拦截器继承HandlerInterceptorAdapter实现
preHandle,postHandle,afterCompletion前置拦截,后置拦截,最终拦截