如 果您的 JSP 网页或 Servlet 在运行过程中丢出了例外,而您想捕捉这个例外,除了使用容器 与 JSP 网页中有关例外的捕捉设定方法之外(例如设定 web.xml 的<error-page>标签,或是设 定 JSP 网页"page"指令元素的"errorPage"属性),您也可以在 DispatcherServlet 的定义档中 设 定 错 误 处 理 网 页 , 设 定 一 个 ExceptionResolver 的 Bean 实 例 , 例 如 使 用 org.springframework.web.servlet.handler.SimpleMappingExceptionResolver,一 个设定的 例子如下所示:
... <bean id="viewResolver" class="org.springframework.web.servlet. →view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="exceptionResolver" class="org.springframework.web.servlet. →handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.sql.SQLException"> sqlexception </prop> <prop key="java.sql.IOException"> ioexception </prop> </props> </property> </bean> ...
DispatcherServlet 会自动应用 ExceptionResolver,并在例外发生时使用指定的网页来显示错 误讯息, 例如在上 面的设定 中 只 要发生了 SQLException ,就会 连接至 /WEB-INF/jsp/sqlexception.jsp , 而 发 生 了IOException , 就 会 连 接 至 /WEB-INF/jsp/ioexception.jsp。