spring学习篇之SpringMVC补充
1. SpringMVC的拦截器
1.1拦截器的作用
SpringMVC的拦截器的作用类似于Servlet中的过滤器Filter,用于对处理器的预处理和后处理。
将拦截器(Interceptor)按照一定的顺序连接成一条链,称为拦截器链(Interceptor chain),在访问被拦截的方法或字段的时候,拦截器链中的Interceptor会按照顺序被调用,Interceptor也是aop思想的具体实现。
1.2 Interceptor和Filter的区别
1.3 拦截器使用
自定义拦截器的步骤:
1.创建拦截器类实现HandlerInterceptor接口
2.配置拦截器
3.使用
//自定义Interceptor
public class TestInterceptor implements HandlerInterceptor{
//三个方法,根据需要实现
preHandle();//目标方法执行之前
postHandle();//目标方法执行之后,视图对象返回之前
afterCompletion();//整个流程执行完之后
}
//spring-mvc.xml配置
<mvc:interceptors>
<mvc:interceptor>
//对哪些资源进行拦截
<mvc:mapping Path="/**"/>
<bean class="com.test.TestInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
1.4 拦截器方法的说明
2. SpringMVC的异常处理
2.1 异常处理思路
系统中的异常通常包括两种,预期异常和运行时异常RuntimeException,前者通过捕获异常,或者通过代码规范来减少。
系统的Dao层,Service层和Controller层都可能会出现异常,通过Throws Exception向上抛出,最后由Spring前端控制器交给异常处理器进行处理。如下图所示:
2.2 异常处理方式
1.使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver
2.实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器
2.3 SimpleMappingExceptionResolver
SpringMVC已经定义好了该类型转换器,在使用时,可以根据项目情况进行相应异常与视图的映射配置
//
<!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
2.4 自定义异常处理
步骤:
1.创建异常处理器去实现HandlerExceptionResolver接口
2.配置异常处理器
3.编写异常页面
4.使用
public class TestHandlerExceptionResolver implements HandlerExceptionResolver{
//参数Exception:异常对象
//返回值ModelAndView:跳转的错误视图
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
ModelAndView modelAndView = new ModelAndView();
if(e instanceof TestException) {
modelAndView.addObject("info","自定义异常");
}else if(e instanceof ClassCastException){
modelAndView.addObject("info","类型转换异常");
}
modelAndView.setViewName("error");
return modelAndView;
}
}
//配置异常处理器
</bean class="com.test.TestHandlerExceptionResolver"/>