Custom Error Pages with Spring MVC

1. Overview

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.

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

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

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

2. The Simple Steps

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 codeFor 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

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

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

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

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.

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.

4. The Controller

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

@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

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 :

<%@ 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

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

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’.

Let’s see what happens when one of handler methods throws a NullPointerException. We add the following method to 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’.

7. Conclusion

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

Related posts:

Java Program to Implement Pollard Rho Algorithm
Java – Reader to Byte Array
Changing Annotation Parameters At Runtime
Hướng dẫn Java Design Pattern – Null Object
How to Read HTTP Headers in Spring REST Controllers
Java Program to Implement Segment Tree
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Introduction to Using Thymeleaf in Spring
Pagination and Sorting using Spring Data JPA
Consuming RESTful Web Services
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Represent Graph Using Incidence Matrix
Java Program to Implement Double Ended Queue
Java Program to Perform Complex Number Multiplication
Tạo chương trình Java đầu tiên sử dụng Eclipse
Java Program to Generate a Random Subset by Coin Flipping
Upload and Display Excel Files with Spring MVC
Xử lý ngoại lệ trong Java (Exception Handling)
Java Program to Implement Karatsuba Multiplication Algorithm
Java Program to Check whether Undirected Graph is Connected using BFS
How to Kill a Java Thread
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Find Number of Articulation points in a Graph
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Disable DNS caching
LinkedList trong java
Spring Boot: Customize Whitelabel Error Page
Java Program to Perform Search in a BST
Hướng dẫn Java Design Pattern – Bridge
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Service Registration with Eureka