本篇文章给大家带来的内容是关于如何使用Spring MVC显示自定义的404 Not Found页面,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
不知道大家对千篇一律的404 Not Found的错误页面是否感到腻歪了?其实通过很简单的配置就能够让Spring MVC显示您自定义的404 Not Found错误页面。
在WEB-INF的web.xml里添加一个新的区域:

意思是一旦有404错误发生时,显示resouces文件夹下的404.jsp页面。
1 2 3 4 | <error-page>
<error-code>404</error-code>
<location>/resources/404.jsp</location>
</error-page>
|
登录后复制
现在可以随意开发您喜欢的个性化404错误页面了。


完毕之后,随便访问一个不存在的url,故意造成404错误,就能看到我们刚才配置的自定义404 Not Found页面了。

如果想在Spring MVC里实现一个通用的异常处理逻辑(Exception handler), 能够捕捉所有类型的异常,比如通过下面这种方式抛出的异常,可以按照下面介绍的步骤来做。

1. 新建一个类,继承自SimpleMappingExceptionResolver:
1 2 3 4 5 6 7 8 9 10 11 | 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();
}
|
登录后复制
2. 在Spring MVC的Servlet配置文件里,将刚才创建的类作为一个Bean配置进去:

Bean的ID设置为simpleMappingExceptionResolver,class设置为步骤一创建的类的包含namespace的全名。创建一个名为defaultErrorView的property,其value为generic_error, 指向一个JSP view:generic_error.jsp。
1 2 3 4 5 6 7 8 | <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的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 | <%@ 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>
|
登录后复制
现在可以做测试了。我之前通过下列语句抛了一个异常:
1 | throw new Exception( "Generic Exception raised by Jerry" );
|
登录后复制
这个异常成功地被我自己实现的异常处理类捕捉到,并显示出我自定义的异常显示页面:

以上是如何使用Spring MVC显示自定义的404 Not Found页面的详细内容。更多信息请关注PHP中文网其他相关文章!