如果我们在使用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结合的更紧密,可扩展的更多。