拦截器技术应用
1、概述
Spring Web中的拦截器(Interceptor)基于回调机制,可以在目标方法执行之前,先进行业务检测,满足条件则放行,不满足条件则进行拦截,拦截器原理分析如下图所示:
2、拦截器定义
基于Spring MVC模块提供的HandlerInterceptor接口规范定义拦截器,对特定请求进行拦截,例如检测请求访问时间,关键代码如下,
package com.jt.web.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
public class TimeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("==preHandler==");
LocalTime now=LocalTime.now();//JDK8中的时间对象
int hour=now.getHour();//获取当前时间对应小时
System.out.println("hour="+hour);
if(hour<=6||hour>=23)
throw new RuntimeException("请在6~17点进行访问");
return true;//false表示请求到此结束,true表示执行执行链中的下一个对象
}
}
3、拦截器配置
定义配置类,实现对拦截器的注册,关键代码如下。
package com.jt.web.config;
import com.jt.web.interceptor.TimeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器,并且设置要拦截的路径
registry.addInterceptor(new TimeInterceptor())
.addPathPatterns("/demo/");//要拦截的路径
}
}
4、访问测试
启动服务,对于url中path以/demo/开头的进行访问测试,检测请求是否被拦截处理了。
http://localhost:8080/demo/