不知道大家對千篇一律的404 not found的錯誤頁面是否感到膩歪了?其實通過很簡單的配置就能夠讓spring mvc顯示您自定義的404 not found錯誤頁面。
在web-inf的web.xml里添加一個新的區域:
意思是一旦有404錯誤發生時,顯示resouces文件夾下的404.jsp頁面。
1
2
3
4
5
6
7
|
<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
12
13
14
15
16
17
18
19
20
21
|
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
9
10
11
12
13
14
15
|
<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
13
14
15
16
17
18
19
20
21
22
23
|
<%@ 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");
這個異常成功地被我自己實現的異常處理類捕捉到,并顯示出我自定義的異常顯示頁面:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000016758927