一般指的是在浏览器页面向服务端发出请求后,拦截请求,对请求进行一系列的操作;或者在服务器返回数据时,在数据到达浏览器界面前,做一些操作,来完成功能的增强。
使用场景:解决请求的共性问题,如:乱码问题、权限验证问题等
public class TestInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
命名空间
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<!--注册拦截器-->
<mvc:interceptors>
<!--注册-->
<bean class="com.imooc.test.interceptor.TestInterceptor"></bean>
</mvc:interceptors>
<!--注册拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--匹配规则-->
<mvc:mapping path="/viewAll.form"/>
<!--注册-->
<bean class="com.imooc.test.interceptor.TestInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class TestInterceptor2 implements WebRequestInterceptor {
//没有返回值,不能终止请求
public void preHandle(WebRequest webRequest) throws Exception {
}
public void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {
}
public void afterCompletion(WebRequest webRequest, Exception e) throws Exception {
}
}
在请求被处理之前调用。是否需要将当前的请求拦截下来,返回true请求继续运行,返回false请求终止(包括action层也会终止),Object arg
代表被拦截的请求的目标对象。
在请求被处理之后调用
在请求处理结束后调用,用作资源销毁,方法不常用。