不知道大家对千篇一律的404 Not Found的错误页面是否感到腻歪了?其实通过很简单的配置就能够让Spring MVC显示您自定义的404 Not Found错误页面。
在WEB-INF的web.xml里添加一个新的区域:
1. 新建一个类,继承自SimpleMappingExceptionResolver:
public class GlobalDefaultExceptionHandler extends SimpleMappingExceptionResolver { public GlobalDefaultExceptionHandler(){ System.out.println("GlobalDefaultExceptionHandler constructor called!"); } @Override public String buildLogMessage(Exception ex, HttpServletRequest request) { System.out.println("Exception caught by Jerry"); ex.printStackTrace(); return "Spring MVC exception: " + ex.getLocalizedMessage(); }
Bean的ID设置为simpleMappingExceptionResolver,class设置为步骤一创建的类的包含namespace的全名。创建一个名为defaultErrorView的property,其value为generic_error, 指向一个JSP view:generic_error.jsp。
<bean id="simpleMappingExceptionResolver" class="com.sap.exception.GlobalDefaultExceptionHandler"> <property name="exceptionMappings"> <map> <entry key="Exception" value="generic_error"></entry> </map> </property> <property name="defaultErrorView" value="generic_error"/> </bean>
generic_error.jsp的源代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Generic Error Page of Jerry</title> </head> <body> <h2>Unknown Error Occured, please contact Wang, Jerry.</h2> </body> </html>
现在可以做测试了。我之前通过下列语句抛了一个异常:
throw new Exception(“Generic Exception raised by Jerry”);
这个异常成功地被我自己实现的异常处理类捕捉到,并显示出我自定义的异常显示页面: