溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring MVC中怎么自定義404 Not Found頁面

發(fā)布時(shí)間:2021-08-13 14:16:53 來源:億速云 閱讀:120 作者:Leah 欄目:編程語言

這篇文章給大家介紹Spring MVC中怎么自定義404 Not Found頁面,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

在WEB-INF的web.xml里添加一個(gè)新的區(qū)域:

Spring MVC中怎么自定義404 Not Found頁面

意思是一旦有404錯(cuò)誤發(fā)生時(shí),顯示resouces文件夾下的404.jsp頁面。

<error-page><error-code>404</error-code><location>/resources/404.jsp</location></error-page>

現(xiàn)在可以隨意開發(fā)您喜歡的個(gè)性化404錯(cuò)誤頁面了。

Spring MVC中怎么自定義404 Not Found頁面

Spring MVC中怎么自定義404 Not Found頁面

完畢之后,隨便訪問一個(gè)不存在的url,故意造成404錯(cuò)誤,就能看到我們剛才配置的自定義404 Not Found頁面了。

Spring MVC中怎么自定義404 Not Found頁面

如果想在Spring MVC里實(shí)現(xiàn)一個(gè)通用的異常處理邏輯(Exception handler), 能夠捕捉所有類型的異常,比如通過下面這種方式拋出的異常,可以按照下面介紹的步驟來做。

Spring MVC中怎么自定義404 Not Found頁面

1. 新建一個(gè)類,繼承自SimpleMappingExceptionResolver:

public class GlobalDefaultExceptionHandler extendsSimpleMappingExceptionResolver {public GlobalDefaultExceptionHandler(){
System.out.println("GlobalDefaultExceptionHandler constructor called!");
}@Overridepublic 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配置文件里,將剛才創(chuàng)建的類作為一個(gè)Bean配置進(jìn)去:

Spring MVC中怎么自定義404 Not Found頁面

Bean的ID設(shè)置為simpleMappingExceptionResolver,class設(shè)置為步驟一創(chuàng)建的類的包含namespace的全名。創(chuàng)建一個(gè)名為defaultErrorView的property,其value為generic_error, 指向一個(gè)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><h3>Unknown Error Occured, please contact Wang, Jerry.</h3></body></html>

現(xiàn)在可以做測試了。我之前通過下列語句拋了一個(gè)異常:

throw new Exception("Generic Exception raised by Jerry");

這個(gè)異常成功地被我自己實(shí)現(xiàn)的異常處理類捕捉到,并顯示出我自定義的異常顯示頁面:

Spring MVC中怎么自定義404 Not Found頁面

關(guān)于Spring MVC中怎么自定義404 Not Found頁面就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI