spring boot 项目重新搭建----------mvc配置:拦截器

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前置拦截,后置拦截,最终拦截

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值