如果我們在使用Spring MVC的過程中,想自定義異常頁面的話,我們可以使用DispatcherServlet來指定異常頁面,具體的做法很簡單:
下面看我曾經的一個項目的spring配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 掃描web包,應用Spring的注解 --> <context:component-scan base-package="com.xxx.training.spring.mvc"/> <!-- 配置視圖解析器,將ModelAndView及字符串解析為具體的頁面 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/views/" p:suffix=".jsp"/> <!--定義異常處理頁面--> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.sql.SQLException">outException</prop> <prop key="java.io.IOException">outException</prop> </props> </property> </bean> </beans>
上面的定義異常處理部分的解釋為:只要發生了SQLException或者IOException異常,就會自動跳轉到WEB-INF/views/outException.jsp頁面。
一般情況下我們的outException.jsp頁面的代碼為:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>異常處理頁面</title> </head> <body> <% Exception ex = (Exception) request.getAttribute("Exception");%> <H2>Exception:<%=ex.getMessage()%> </H2> </body> </html>
當然你也可以修改樣式,這個就看個人喜好了、
另外記得要在web.xml也使用類似下面的方式處理異常哦。:
<error-page> <error-code>404</error-code> <location>/WEB-INF/pages/404.jsp</location> </error-page> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/WEB-INF/pages/exception.jsp</location> </error-page>
因為這兩個異常處理的維度是不一樣的,簡單說,spring的resolver是spring內部使用的,而web。xml里的是整個webapp共同使用的。
建議兩個都配置上,
因為spring的resolver可以和spring結合的更緊密,可擴展的更多。