Custom Error Pages with Spring MVC – 使用Spring MVC的自定义错误页面

最后修改: 2016年 11月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

A common requirement in any web application is customized error pages.

在任何网络应用中,一个常见的要求是定制错误页面。

For instance, suppose you’re running a vanilla Spring MVC app on top of Tomcat. A user enters an invalid URL in his browser and is shown a not so user-friendly blue and white stack trace – not ideal.

例如,假设你在Tomcat上面运行一个香草的Spring MVC应用。一个用户在他的浏览器中输入了一个无效的URL,并显示了一个不太友好的蓝白相间的堆栈跟踪–这并不理想。

In this tutorial, we’ll set up customized error pages for a few HTTP error codes.

在本教程中,我们将为几个HTTP错误代码设置自定义错误页面。

The working assumption is that the reader is fairly comfortable working with Spring MVC; if not, this is a great way to start.

我们的工作假设是,读者对Spring MVC的工作相当熟悉;如果不是,这是一个很好的开始方式

This article focuses on Spring MVC. Our article Customize Whitelabel Error Page describes how to create a custom error page in Spring Boot.

本文主要介绍Spring MVC。我们的文章自定义白标签错误页描述了如何在Spring Boot中创建自定义错误页。

2. The Simple Steps

2.简单的步骤

Let’s start with the simple steps we’re going to follow here:

让我们从这里要遵循的简单步骤开始。

  1. Specify a single URL /errors in web.xml that maps to a method that would handle the error whenever an error is generated
  2. Create a Controller called ErrorController with a mapping /errors
  3. Figure out the HTTP error code at runtime and display a message according to the HTTP error code. For instance, if a 404 error is generated, then the user should see a message like ‘Resource not found’ , whereas for a 500 error, the user should see something on the lines of ‘Sorry! An Internal Server Error was generated at our end’

3. The web.xml

3、web.xml

We start by adding the following lines to our web.xml:

我们首先在我们的web.xml中添加以下几行:

<error-page>
    <location>/errors</location>
</error-page>

Note that this feature is only available in Servlet versions greater than 3.0.

请注意,这个功能只适用于大于3.0的Servlet版本。

Any error generated within an app is associated with a HTTP error code. For example, suppose that a user enters a URL /invalidUrl into the browser, but no such RequestMapping has been defined inside of Spring. Then, a HTTP code of 404 generated by the underlying web server. The lines that we have just added to our web.xml tells Spring to execute the logic written in the method that is mapped to the URL /errors.

应用程序中产生的任何错误都与HTTP错误代码有关。例如,假设用户在浏览器中输入了一个URL/invalidUrl,但Spring中没有定义这样的RequestMapping。那么,底层Web服务器就会生成404的HTTP代码。我们刚才在web.xml中添加的几行,告诉Spring执行映射到URL/errors.的方法中所编写的逻辑。

A quick side-note here – the corresponding Java Servlet configuration doesn’t unfortunately have an API for setting the error page – so in this case, we actually need the web.xml.

这里有一个简短的旁注–不幸的是,相应的Java Servlet配置并没有设置错误页面的API–所以在这种情况下,我们实际上需要web.xml

4. The Controller

4.控制器

Moving on, we now create our ErrorController. We create a single unifying method that intercepts the error and displays an error page:

继续,我们现在创建我们的ErrorController。我们创建一个统一的方法,拦截错误并显示一个错误页面。

@Controller
public class ErrorController {

    @RequestMapping(value = "errors", method = RequestMethod.GET)
    public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
        
        ModelAndView errorPage = new ModelAndView("errorPage");
        String errorMsg = "";
        int httpErrorCode = getErrorCode(httpRequest);

        switch (httpErrorCode) {
            case 400: {
                errorMsg = "Http Error Code: 400. Bad Request";
                break;
            }
            case 401: {
                errorMsg = "Http Error Code: 401. Unauthorized";
                break;
            }
            case 404: {
                errorMsg = "Http Error Code: 404. Resource not found";
                break;
            }
            case 500: {
                errorMsg = "Http Error Code: 500. Internal Server Error";
                break;
            }
        }
        errorPage.addObject("errorMsg", errorMsg);
        return errorPage;
    }
    
    private int getErrorCode(HttpServletRequest httpRequest) {
        return (Integer) httpRequest
          .getAttribute("javax.servlet.error.status_code");
    }
}

5. The Front-End

5.前端

For demonstration purposes, we will be keeping our error page very simple and compact. This page will only contain a message displayed on a white screen. Create a jsp file called errorPage.jsp :

出于示范目的,我们将保持我们的错误页面非常简单和紧凑。这个页面将只包含一条显示在白色屏幕上的信息。创建一个jsp文件,名为errorPage.jsp :

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${errorMsg}</h1>
</body>
</html>

6. Testing

6.测试

We will simulate two of the most common errors that occur within any application: the HTTP 404 error, and HTTP 500 error.

我们将模拟任何应用程序中最常见的两个错误:HTTP 404错误,和HTTP 500错误。

Run the server and head on over to localhost:8080/spring-mvc-xml/invalidUrl.Since this URL doesn’t exist, we expect to see our error page with the message ‘Http Error Code : 404. Resource not found’.

运行服务器并前往localhost:8080/spring-mvc-xml/invalidUrl.因为这个URL不存在,我们希望看到我们的错误页面,并显示’Http Error Code :404.没有找到资源’。

Let’s see what happens when one of handler methods throws a NullPointerException. We add the following method to ErrorController:

让我们看看当一个处理方法抛出NullPointerException时会发生什么。我们在ErrorController中添加以下方法:

@RequestMapping(value = "500Error", method = RequestMethod.GET)
public void throwRuntimeException() {
    throw new NullPointerException("Throwing a null pointer exception");
}

Go over to localhost:8080/spring-mvc-xml/500Error. You should see a white screen with the message ‘Http Error Code : 500. Internal Server Error’.

转到localhost:8080/spring-mvc-xml/500Error。你应该看到一个白色的屏幕,上面写着’Http Error Code :500.内部服务器错误’。

7. Conclusion

7.结论

We saw how to set up error pages for different HTTP codes with Spring MVC. We created a single error page where an error message is displayed dynamically according to the HTTP error code.

我们看到如何用Spring MVC为不同的HTTP代码设置错误页面我们创建了一个错误页面,根据HTTP错误代码动态地显示错误信息。