如 果您的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>
...
<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。