好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解如何让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

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://HdhCmsTestw3.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测试数据/a/1190000016758927

查看更多关于详解如何让Spring MVC显示自定义的404 Not Found页面的详细内容...

  阅读:18次