美文网首页
Springboot使用拦截器记录

Springboot使用拦截器记录

作者: wayne_wzy | 来源:发表于2018-04-12 11:02 被阅读0次

概述

关于在使用Springboot的使用过程中,对于Spring中的aop面向切面编程中的几个主要使用场景做了一些记录

1. Springboot 中配置拦截器

拦截器中用到bean注入时,需要提前加载bean注解(LoginInterceptor为自己编写的登录拦截器)
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public LoginInterceptor getLoginInterceptor() {
        return new LoginInterceptor();
    }

    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getLoginInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
    }

Springboot中的拦截器实现HandlerInterceptor,重写里面的几个方法:
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        //处理一些路径的放行
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

2.异常处理器(全局异常处理)

@ControllerAdvice
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response handle(Exception e) {
        if (e instanceof BusinessException) {
            return HttpUtil.respondFail(((BusinessException) e).getCode(), e.getMessage());
        } else if (e instanceof NullPointerException) {
            e.printStackTrace();
            return HttpUtil.respondFail(500, "服务器繁忙");
        }
        e.printStackTrace();
        return HttpUtil.respondFail(500, "服务器开小差了");
    }
}

3.使用aop实现统一日志记录打印

@Aspect
@Component
public class HttpAspect {
    private static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.*.controller..*.*(..))")
    public void logHttp() {
    }

    @Around("logHttp()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        Gson gson = new Gson();
        logger.info("请求结束,controller的返回值是 " + gson.toJson(result));
        return result;
    }

}

Created By 2018 - 04 -12

相关文章

网友评论

      本文标题:Springboot使用拦截器记录

      本文链接:https://www.haomeiwen.com/subject/otrxkftx.html