springboot 2 http拦截器

2018-10-14  本文已影响0人  SetsunaHao
  1. 新建一个拦截器类,继承HandlerInterceptorAdapter, 重写以下三个方法即可
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

public class HttpInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(HttpInterceptor.class);

    private static final String START_TIME = "requestStartTime";

    /**
     * 拦截请求url和请求参数
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求时间和请求参数
        String url = request.getRequestURI();
        Map<String, String[]> parameterMap = request.getParameterMap();
        long start = System.currentTimeMillis();
       //为了方便所以new 了一个ObjectMapper,建议不要这么做,做成单例调用即可
        logger.info("request start | url : [{}], params : [{}]", url, new ObjectMapper().writeValueAsString(parameterMap));
        //放入请求初始时间
        request.setAttribute(START_TIME, start);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 请求结束后,计算url花费时间
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url  = request.getRequestURI();
        long start = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        long costTime = end - start;
        logger.info("request finished | url : [{}], costTime : [{}] ms ", url, costTime);
    }

}

2.新建一个类实现WebMvcConfigurer接口,将拦截器注册上即可,这是2.x的做法,

1.x是继承WebMvcConfigurerAdapter(在2.x中已过时)

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HttpInterceptor()).addPathPatterns("/**");
    }
}
上一篇下一篇

猜你喜欢

热点阅读