Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理;
这篇博客我们只说第一种方式:
实现代码如下:
模拟一个被除数不能为0 的异常
//异常 @RequestMapping("/exception") public String doException(){ int num=5/0; return "suecssful"; }
xml配置文件的代码:
//包扫描器
<context:component-scan base-package="day09"></context:component-scan> <!--系统异常处理--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="error"></property> <property name="exceptionAttribute" value="ex"></property> </bean>
//视图解析器 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven></mvc:annotation-driven>
创建一个error.jsp页面 发生错误跳转到这里
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h2>出错了</h2> ${ex.message} </body> </html>
成功就到successful界面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h2>成功</h2> ${msg} ${name} </body> </html>