一、拦截器Interceptor
- SpringMVC 拦截器用于对URL请求进行前置/后置过滤
- Intercetpor与Filter功能相似,区别是拦截器是Spring提供,与IOC天
然兼容,Filter是J2EE的标准更加重量级 - Interceptor底层就是基于Spring AOP面向切面编程实现的
- Interceptor应用场景很多,例如:权限验证,表单校验,日志输出....
二、开发思路
- 编写类实现HandlerInterceptor接口
- Maven依赖servlet-api(scope=compile)
- application配置过滤地址
三、HandlerInterceptor接口
- HandlerInterceptor接口定义了3个要实现的方法
- preHandle - 前置校验,在运行目标方法前执行
- postHandle - 后置校验,在目标方法运行后执行
- afterCompletion - 完成后校验,在产生渲染结果后执行,即页面渲染之后进行执行
四、代码实现
1.编写类
public class SecurityInterceptor implements HandlerInterceptor { public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception { System.out.println(request.getRequestURL() + "前置处理"); String token = request.getHeader("token"); if(token == null){ response.sendError(403,"Token Not Found!"); return false; } return true; } public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(request.getRequestURL() + "处理完成"); } public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(request.getRequestURL() + "已渲染输出"); } }
2.maven依赖
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <!-- compile只在编译时加载这个依赖,运行时不加载 runtime只在运行时加载这个依赖,编译时不加载 provided 则是编译与运行时都加载,这是默认项 --> <scope>compile</scope> </dependency>
3.application配置
<mvc:interceptors> <!--配置拦截器--> <mvc:interceptor> <!--拦截器拦截的地址,/**代表所有地址 也可以书写/xxx某个具体的地址 如果有多个URL需要拦截,可以写多个mvc:mapping标签--> <mvc:mapping path="/**"/> <mvc:mapping path="/login.html"/> <mvc:mapping path="/reg"/> <!-- exclude-mapping是排除地址,必须以/开头,后面增加匹配字符串即可 exclude-mapping通常是排除掉静态资源 --> <mvc:exclude-mapping path="/**.ico"/> <mvc:exclude-mapping path="/**.jpg"/> <mvc:exclude-mapping path="/**.gif"/> <bean class="com.itlaoqi.springmvc.interceptor.SecurityInterceptor"/> </mvc:interceptor> <!--某个URL遇到多个拦截器时,会按照配置顺序依次执行,如果前面preHandle没有通过,则会全部中断--> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.itlaoqi.springmvc.interceptor.SecurityInterceptor1"/> </mvc:interceptor> </mvc:interceptors>