SpringMVC拦截器
拦截器知识
拦截器(Interceptor)用于对URL请求进行前置/后置过滤
Interceptor与Filter用途相似但实现方式不同
Interceptor底层就是基于Spring AOP面向切面编程实现
拦截器开发流程
Maven添加依赖包servlet-api
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency>
实现HandlerInterceptor接口
接口会实现三个方法,拦截的时间分别为:
preHandle-前置执行处理,请求产生之后,Controller处理之前。
postHandle - 目标资源已被Spring MVC框架处理,Controller处理之后,方法的return执行完立马执行这个拦截器。
afterCompletion - 响应文本已经产生,产生响应文本之后。
public class MyInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println(request.getRequestURL() + "-准备执行");return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println(request.getRequestURL() + "-目标处理成功");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println(request.getRequestURL() + "-响应内容已产生");}
}
applicationContext配置过滤地址。
mapping path=“/**”: 拦截所有地址
<bean class=“com.imooc.restful.interceptor.AccessHistoryInterceptor”/>: 拦截之后负责处理的方法类。
<mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><mvc:exclude-mapping path="/resources/**"/><bean class="com.imooc.restful.interceptor.AccessHistoryInterceptor"/></mvc:interceptor></mvc:interceptors>
/<mvc:exclude-mapping path=“/resources/**”/>:哪个路径下的文件不启用拦截器。