springmvc----拦截器----笔记
定义拦截器
实现HandlerInterceptor接口
package top.demo.test.Interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor{
/*
* 框架调用doDispatch之前会遍历所有的拦截器 调用其preHandle
* 如果某一个拦截器返回false将不执行doDispatch
*
* preHandle在方法doDispatch之前调用
* postHandle在处理控制器方法之后 渲染视图之前调用 注意参数有modelAndView可以修改渲染前的数据
* afterCompletion在渲染视图之后调用 可以释放资源用
*
*
* */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion");
}
}
spring配置文件中注册
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="top.demo.test"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:interceptors>
<bean class="top.demo.test.Interceptor.MyInterceptor"></bean>
<!--
多个拦截器的执行顺序,preHandle按配置的先后执行,其他两个则按配置先后的反序执行
还有这种配置方式,指定包含哪些页面路径 (<mvc:mapping path=""/>)或者 排除哪些(<mvc:exclude-mapping path=""/> )
<mvc:interceptor>
<mvc:exclude-mapping path=""/>
<bean></bean>
</mvc:interceptor>
-->
</mvc:interceptors>
</beans>
且