Spring MVC通过 HandlerExceptionResolver处理程序的异常,包括 Handler 的映射、数据绑定以及目标方法执行时发生的异常。
SpringMVC提供的 HandlerExceptionResolver 的实现类
作用 将报错页面调整为符合客户需求(简单明了 格式优美等)的页面
在Controller层中增加方法:
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView mav = new ModelAndView("error");
System.out.println("=======handleException=========");
mav.addObject("exception", e);
return mav;
}
在使用@ExceptionHandler进行异常处理时,不可以将exception直接设置到方法参数中声明的modle, 必须返回ModelAndView
@ExceptionHandler 只能作用本类中的异常信息处理
如果处理工程中所有的异常信息, 当Handler找不到@ExceptionHandler标注的方法时,需要使用@ControllerAdvice标注的类中@ExceptionHandler来处理。
如下:
@ControllerAdvice
public class MyExceptionHandler{
@ExceptionHandler(Throwable.class)
public ModelAndView handleException(Throwable e) {
ModelAndView mav = new ModelAndView("error");
System.out.println("=======handleException=========");
mav.addObject("exception", e);
return mav;
}
在xml中通过配置信息进行异常处理
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
如果错误为java.lang.ArrayIndexOutOfBoundsException直接跳转到error.jsp页面
在jsp页面
<div align="center">
<h2>ERROR PAGE</h2>
<div>
errorINof:${exception }
</div>
可显示出错误原因 注意:errorINof:${exception }
为默认写法 若改变exception 名称 如errorINof:${myException }
则需再增加配置<property name="exceptionAttribute" value="myException">
如下:
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="myException"></property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>