Spring mvc拦截器
大概流程是:
1:浏览器段发送http://localhost:9808/项目名/index.jsp 请求
2:springMVC中转发器 DispatcherServlet 进行转发处理
3:转发器 调用映射器在注解@requestMapping中寻找请求路径,如果找不到就报错
4:映射器将找的路径的方法,返回给 转发器
5:转发器调用适配器
6:适配器 调用方法,并且开始执行
7: 方法返回字符串,并通过适配器返回给转发器
8:转发器把返回的字符串返回给 视图解析器
9:视图解析器找到页面,并且填充数值,返回给转发器
10 :转发器把返回的页面,传给浏览器
11 :浏览器端请求执行完毕
拦截器 在在映射器端进行执行比较好,如果有需要拦截的请求,会首先通过映射器,映射器你返回false的时候,映射器以后的无效请求就不会继续执行。如果映射器返回true,然后继续执行,在拦截器写入我们想做的事情。
spring映射器在 spring-webmvc.jar包中的,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
spring适配器在spring-webmvc.jar包中的 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
映射器和适配器默认是spring管理的,一旦手动注册了,需要两个同时注册,不能一个手动,另一个让spring管理
拦截器的实现类必须实现接口HandlerInterceptor
public class FristInterceptor implements HandlerInterceptor {
//页面渲染,释放资源
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("FristInterceptot afterCompletion");
}
//方法执行后,渲染执行前,可以对请求域中的属性或者视图修改
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("FristInterceptot postHandle");
}
//方法执行前,返回false表示拦截,方法将不会继续执行,一般用作权限拦截,事物,日志
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("FristInterceptot preHandle");
return true;
}
如果你导入mvc文件可以使用已下方式
<!-- 配置LocaleChangeInterceptor-->
<mvc:interceptors>
<!-- 注册自定义拦截器 -->
<bean class="com.china.springmvc.Interceptor.FristInterceptor"></bean>
</mvc:interceptors>