基于Spring MVC模块提供的HandlerInterceptor接口规范定义拦截器,对特定请求进行拦截,例如检测请求访问时间,关键代码如下
package com.jt.web.interceptor;
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.jt.web.config;
@Configuration
public class SpringWebConfig implements WebMvcConfigurer{//web.xml
//配置spring mvc 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TimeAccessInterceptor())
.addPathPatterns("/param/*");//写访问的路径
}
}