概述:
Spring Web 中的拦截器(Interceptor)基于回调机制,能够在指标办法执行之前,
先进行业务检测,满足条件则放行,不满足条件则进行拦挡,拦截器原理剖析如下图所示:
拦截器定义
通过拦截器拦挡对 Spring Web Handler 进行工夫拜访拦挡,其要害代码定义如下
package com.cy.pj.common.web;/*** Spring MVC 中拦截器* @author Administrator*/public class TimeAccessInterceptor implements HandlerInterceptor {/*** preHandle 在管制层指标办法执行之前执行*/ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //testRequestInfo(request,handler); LocalTime now=LocalTime.now();//JDK8 中的工夫对象 int hour=now.getHour();//获取以后工夫对应小时 //System.out.println("hour="+hour); log.info("hour {}",hour); if(hour<=6||hour>=22) throw new RuntimeException("请在 6~10 点进行拜访"); return true; }}
拦截器配置
定义配置类,实现对拦截器的注册,要害代码如下
package com.cy.pj.sys.web.config;@Configurationpublic class SpringWebConfig implements WebMvcConfigurer{//web.xml//配置 spring mvc 拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new TimeAccessInterceptor()) .addPathPatterns("/notice/**");}}