当前位置: 首页 > 专题 > > 内容页

Spring之拦截器

来源:程序员客栈 2023-08-03 10:23:45

一、SpringMvc拦截器


(资料图片)

springmvc.xml配置

           

拦截器MyInterceptor类代码(统计接口访问次数)

public class MyInterceptor extends HandlerInterceptorAdapter {    private ThreadLocal stopWatchLocal = new ThreadLocal();     @Autowired   protected SystemInterfaceLogService systemInterfaceLogService;   @Override   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)         throws Exception {      StopWatch stopWatch = new StopWatch(handler.toString());      stopWatchLocal.set(stopWatch);      stopWatch.start("stopWatchLocal");      return super.preHandle(request, response, handler);   }   @Override   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)         throws Exception {      Long time = 0L;      StopWatch stopWatch = stopWatchLocal.get();      if (stopWatch != null) {         if (stopWatch.isRunning()) {            stopWatch.stop();            time = stopWatch.getTotalTimeMillis();            stopWatchLocal.remove();         }      }      String currentPath = request.getRequestURI();      String requestType = request.getMethod();      String queryString = "";      if(requestType.equals("GET")){         queryString = request.getQueryString();         queryString = queryString == null ? "" : "?" + queryString;      }else{         BufferedReader br=request.getReader();         String inputLine = "";         while ((inputLine = br.readLine()) != null) {            queryString += inputLine;         }         br.close();      }      SystemInterfaceLogDtl data = new SystemInterfaceLogDtl();      data.setUrlId(UUID.randomUUID().toString());      data.setSystemType("test");

data.setRequestUrlName(currentPath.substring(currentPath.lastIndexOf("/")+1,currentPath.length()));      

//请求接口路径

data.setRequestUrl(currentPath);

//请求接口参数

data.setRequeryParm(queryString);

//请求接口时长(ms)

data.setRequeryTime(time); String date = DateUtils.convertToTime(new Date()); data.setCreateTime(date); data.setLastTime(date); systemInterfaceLogService.insertSystemInterfaceLog(data); super.afterCompletion(request, response, handler, ex);

}

@Override public void afterPropertiesSet() throws Exception { }}

二、SpringBoot拦截器

添加web过滤器

1、添加web 过滤器,管理过滤的类,以及过滤的请求路径

2、实现WebMvcConfigurer类,复写父类的方法 addInterceptors

3、通过registry.addInterceptor拦截类,addPathPatterns拦截路径,excludePathPatterns添加允许路径

@Configurationpublic class addInterceptor implements WebMvcConfigurer {    @Resource    private MyInterceptor authInterceptor;    /**     * 自定义资源映射     *     * @param registry     */    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {    }    /**     * 拦截页面     *     * @param registry     */    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/");    }    /**     * 视图跳转控制器     * @param registry     */    @Override    public void addViewControllers(ViewControllerRegistry registry) {    }    /**     * 默认静态资源处理器     * @param configurer     */    @Override    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {    }    /**     * 配置视图解析器     * @param registry     */    @Override    public void configureViewResolvers(ViewResolverRegistry registry) {    }    /**     * 配置内容裁决的一些选项     * @param configurer     */    @Override    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {    }}

拦截器MyInterceptor类代码(统计接口访问次数)

@Componentpublic class MyInterceptor extendsHandlerInterceptorAdapter {

private ThreadLocal stopWatchLocal = new ThreadLocal();   @Autowired   protected SystemInterfaceLogService systemInterfaceLogService;   @Override   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)         throws Exception {      StopWatch stopWatch = new StopWatch(handler.toString());      stopWatchLocal.set(stopWatch);      stopWatch.start("stopWatchLocal");      return super.preHandle(request, response, handler);   }   @Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)         throws Exception {      Long time = 0L;      StopWatch stopWatch = stopWatchLocal.get();      if (stopWatch != null) {         if (stopWatch.isRunning()) {            stopWatch.stop();            time = stopWatch.getTotalTimeMillis();            stopWatchLocal.remove();         }      }      String currentPath = request.getRequestURI();      String requestType = request.getMethod();      String queryString = "";      if(requestType.equals("GET")){         queryString = request.getQueryString();         queryString = queryString == null ? "" : "?" + queryString;      }else{         BufferedReader br=request.getReader();         String inputLine = "";         while ((inputLine = br.readLine()) != null) {            queryString += inputLine;         }         br.close();      }      SystemInterfaceLogDtl data = new SystemInterfaceLogDtl();      data.setUrlId(UUID.randomUUID().toString());      data.setSystemType("test");

data.setRequestUrlName(currentPath.substring(currentPath.lastIndexOf("/")+1,currentPath.length()));      

//请求接口路径

data.setRequestUrl(currentPath);

//请求接口参数

data.setRequeryParm(queryString);

//请求接口时长(ms)

data.setRequeryTime(time); String date = DateUtils.convertToTime(new Date()); data.setCreateTime(date); data.setLastTime(date); systemInterfaceLogService.insertSystemInterfaceLog(data); super.afterCompletion(request, response, handler, ex);

}

@Override   public void afterPropertiesSet() throws Exception {   }

最近更新