天天看點

如何讓Spring MVC顯示自定義的404 Not Found頁面

不知道大家對千篇一律的404 Not Found的錯誤頁面是否感到膩歪了?其實通過很簡單的配置就能夠讓Spring MVC顯示您自定義的404 Not Found錯誤頁面。

在WEB-INF的web.xml裡添加一個新的區域:

如何讓Spring MVC顯示自定義的404 Not Found頁面
意思是一旦有404錯誤發生時,顯示resouces檔案夾下的404.jsp頁面。

<error-page>

<error-code>404</error-code>

<location>/resources/404.jsp</location>

</error-page>           

現在可以随意開發您喜歡的個性化404錯誤頁面了。

如何讓Spring MVC顯示自定義的404 Not Found頁面
如何讓Spring MVC顯示自定義的404 Not Found頁面

完畢之後,随便通路一個不存在的url,故意造成404錯誤,就能看到我們剛才配置的自定義404 Not Found頁面了。

如何讓Spring MVC顯示自定義的404 Not Found頁面

如果想在Spring MVC裡實作一個通用的異常處理邏輯(Exception handler), 能夠捕捉所有類型的異常,比如通過下面這種方式抛出的異常,可以按照下面介紹的步驟來做。

如何讓Spring MVC顯示自定義的404 Not Found頁面

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();

}           

2. 在Spring MVC的Servlet配置檔案裡,将剛才建立的類作為一個Bean配置進去:

如何讓Spring MVC顯示自定義的404 Not Found頁面

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");

這個異常成功地被我自己實作的異常處理類捕捉到,并顯示出我自定義的異常顯示頁面:

如何讓Spring MVC顯示自定義的404 Not Found頁面

要擷取更多Jerry的原創技術文章,請關注公衆号"汪子熙"或者掃描下面二維碼:

如何讓Spring MVC顯示自定義的404 Not Found頁面
如何讓Spring MVC顯示自定義的404 Not Found頁面