Spring MVC Exception Handling – SimpleMappingExceptionResolver

Assume that the web application is throwing some exception from the backend and it is coming in the UI as below

How bad it is for the user to see this error right?
So we need to handle the exception gracefully in the application.
When we handle it properly , we can display the user friendly message.

Lets see how Spring MVC helps in Exception Handling

In Spring MVC,We can handle exception in many ways but we will see popular 3 ways

1)SimpleMappingExceptionResolver

This is the implementation of HandlerExceptionResolver class.
In this method , Each exception class will be mapped to specific view page.

2)Controller based ExceptionHandler

In this method,All the exceptions thrown by a specific controller can be handled by defining ExceptionHandler methods inside that controller. Any exceptions thrown outside that controller will not be handled here.

3)Global ExceptionHandler

In this method , All the exceptions thrown from any controller in the application can be handled by defining a single class which is annotated with @ControllerAdvice

Enough with the Theory , lets go ahead with each approach Step by Step.

1)SimpleMappingExceptionResolver

We will create a simple Login project to find the user based on user name. and if user enters invalid credentials we will throw an exception and will handle it gracefully.

Project structure

Create custom Exception class

  1. package com.kb.exception;
  2.  
  3. public class InvalidUserException extends RuntimeException{
  4.    
  5.     private static final long serialVersionUID = 1L;
  6.    
  7.     private String errorCode;
  8.     private String errorMessage;
  9.  
  10.     public InvalidUserException(String message) {
  11.         this.errorMessage=message;
  12.     }
  13.    
  14.     public InvalidUserException(String errorCode,String message) {
  15.         this.errorCode = errorCode;
  16.         this.errorMessage=message;
  17.     }
  18.  
  19.     public String getErrorCode() {
  20.         return errorCode;
  21.     }
  22.  
  23.     public String getErrorMessage() {
  24.         return errorMessage;
  25.     }
  26.  
  27. }
package com.kb.exception;

public class InvalidUserException extends RuntimeException{
	
	private static final long serialVersionUID = 1L;
	
	private String errorCode;
	private String errorMessage;

	public InvalidUserException(String message) {
		this.errorMessage=message;
	}
	
	public InvalidUserException(String errorCode,String message) {
		this.errorCode = errorCode;
		this.errorMessage=message;
	}

	public String getErrorCode() {
		return errorCode;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

}

Create the model class which holds user details

  1. package com.kb.model;
  2.  
  3. public class User {
  4.  
  5.     private String userName;
  6.  
  7.     private String password;
  8.  
  9.     public String getUserName() {
  10.         return userName;
  11.     }
  12.  
  13.     public void setUserName(String userName) {
  14.         this.userName = userName;
  15.     }
  16.  
  17.     public String getPassword() {
  18.         return password;
  19.     }
  20.  
  21.     public void setPassword(String password) {
  22.         this.password = password;
  23.     }
  24.  
  25. }
package com.kb.model;

public class User {

	private String userName;

	private String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

Create the login controller class

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.ModelAttribute;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8.  
  9. import com.kb.exception.InvalidUserException;
  10. import com.kb.model.User;
  11.  
  12. @Controller
  13. public class LoginController {
  14.  
  15.     @RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
  16.     public String displayLoginPage(Model model){
  17.         User user = new User();
  18.         model.addAttribute("user", user);
  19.         return "/login";
  20.     }
  21.    
  22.     @RequestMapping(value="/doLogin",method=RequestMethod.POST)
  23.     public String doLogin(@ModelAttribute User user,Model model){
  24.        
  25.         String userName=user.getUserName();
  26.         String password = user.getPassword();
  27.         if("kb".equals(userName) && "1234".equals(password)){
  28.             model.addAttribute("user", user);
  29.             return "/home";
  30.         }
  31.         else{
  32.             //Log the exception
  33.             throw new InvalidUserException("INVALID_USER","User is not Valid for this site");
  34.         }
  35.        
  36.     }
  37.    
  38.     @RequestMapping(value="/getGenericException",method=RequestMethod.GET)
  39.     public String getGenericException(Model model) throws Exception{
  40.  
  41.         throw new Exception();
  42.     }
  43. }
package com.kb.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.exception.InvalidUserException;
import com.kb.model.User;

@Controller
public class LoginController {

	@RequestMapping(value="/displayLoginPage",method=RequestMethod.GET)
	public String displayLoginPage(Model model){
		User user = new User();
		model.addAttribute("user", user);
		return "/login";
	}
	
	@RequestMapping(value="/doLogin",method=RequestMethod.POST)
	public String doLogin(@ModelAttribute User user,Model model){
		
		String userName=user.getUserName();
		String password = user.getPassword();
		if("kb".equals(userName) && "1234".equals(password)){
			model.addAttribute("user", user);
			return "/home";
		}
		else{
			//Log the exception
			throw new InvalidUserException("INVALID_USER","User is not Valid for this site");
		}
		
	}
	
	@RequestMapping(value="/getGenericException",method=RequestMethod.GET)
	public String getGenericException(Model model) throws Exception{

		throw new Exception();
	}
}

In the above controller, we have a method displayLoginPage() which displays the login page.

We also have a method doLogin() which checks the credentials and displays home page if credentials are valid.

If credentials are invalid , we throw an exception InvalidUserException which we handle as below.

There is one more method getGenericException() which is intentionally used to throw some general exception just to show how any unhandled exception is handled automatically through Exception resolver mapping.

Create the spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20.    
  21.     <bean
  22.         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  23.         <property name="exceptionMappings">
  24.             <map>
  25.                 <entry key="InvalidUserException" value="userNotFound"/>
  26.             </map>
  27.         </property>
  28.         <property name="defaultErrorView" value="genericError"/>
  29.     </bean>
  30.    
  31. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb.*" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<map>
                <entry key="InvalidUserException" value="userNotFound"/>
            </map>
		</property>
		<property name="defaultErrorView" value="genericError"/>
	</bean>
	
</beans>

So in the above file, we have defined SimpleMappingExceptionResolver, it has a property called exceptionMappings where we can specify the list of exceptions and their corresponding view page to display.

There is also a property called defaultErrorView which is very useful property,
It maps any other unhandled exceptions in the application to the corresponding view page(genericError.jsp in this case)

Create the login jsp

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  2. <html>
  3. <head>
  4. <title>Spring MVC Exception Handling</title>
  5. </head>
  6.  
  7. <body>
  8.     <h2>Enter below details to Login</h2>
  9.  
  10.     <form:form method="POST" modelAttribute="user" action="doLogin">
  11.         <table>
  12.            
  13.             <tr>
  14.                 <td>Enter your User Name</td>
  15.                 <td><form:input path="userName" /></td>
  16.             </tr>
  17.            
  18.             <tr>
  19.                 <td>Enter your password:</td>
  20.                 <td><form:password path="password"  showPassword="true"/></td>
  21.             </tr>
  22.            
  23.             <tr>
  24.                 <td><input type="submit" name="submit" value="Click here to Login"></td>
  25.             </tr>
  26.         </table>
  27.     </form:form>
  28.  
  29. </body>
  30. </html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>

<body>
	<h2>Enter below details to Login</h2>

	<form:form method="POST" modelAttribute="user" action="doLogin">
		<table>
			
			<tr>
				<td>Enter your User Name</td>
				<td><form:input path="userName" /></td>
			</tr>
			
			<tr>
				<td>Enter your password:</td>
				<td><form:password path="password"  showPassword="true"/></td>
			</tr>
			
			<tr>
				<td><input type="submit" name="submit" value="Click here to Login"></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

Create the home jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Login Success</title>
  9. </head>
  10. <body>
  11.  <div align="center">
  12.         <h2>Welcome ${user.userName}! You have been successfully Logged in.</h2>
  13.   </div>
  14. </body>
  15. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=ISO-8859-1">
<title>Login Success</title>
</head>
<body>
 <div align="center">
        <h2>Welcome ${user.userName}! You have been successfully Logged in.</h2>
  </div>
</body>
</html>

This home jsp is displaed after successful login.

Create the userNotFound jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2> Sorry User is not valid for this site</h2>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> Sorry User is not valid for this site</h2>
</body>
</html>

The above jsp page is displayed when the user enters invalid credentials as we are throwing the InvalidUserException in the controller.

We are also mapping the InvalidUserException inside spring configuration file for the above jsp page.

Create the genericError jsp page

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2> Sorry, some technical error, Please try again</h2>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> Sorry, some technical error, Please try again</h2>
</body>
</html>

The above jsp page is displayed when any other exception apart from InvalidUserException is thrown.

Create the web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Simple Mapping Exception Resolver</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28.     <!-- Loads Spring Security configuration file -->
  29.      <context-param>
  30.         <param-name>contextConfigLocation</param-name>
  31.         <param-value>
  32.             /WEB-INF/spring-mvc.xml,
  33.         </param-value>
  34.     </context-param>
  35. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Simple Mapping Exception Resolver</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Loads Spring Security configuration file -->
	 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
	</context-param>
</web-app>

Create the pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>ExceptionHandling</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>ExceptionHandling Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47.   </dependencies>
  48.   <build>
  49.     <finalName>SimpleMappingExceptionResolver</finalName>
  50.     <plugins>
  51.             <plugin>
  52.                 <groupId>org.apache.maven.plugins</groupId>
  53.                 <artifactId>maven-compiler-plugin</artifactId>
  54.                 <version>2.5.1</version>
  55.                 <configuration>
  56.                     <source>1.8</source>
  57.                     <target>1.8</target>
  58.                 </configuration>
  59.             </plugin>
  60.         </plugins>
  61.   </build>
  62. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>ExceptionHandling</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ExceptionHandling Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
  </dependencies>
  <build>
    <finalName>SimpleMappingExceptionResolver</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Now deploy the project in web server and access the below url

http://localhost:8080/SimpleMappingExceptionResolver/displayLoginPage

Enter username as kb and password as 1234
Home page is displayed, no issues.

Enter invalid credentials , I am giving username as xyz and password as 1111 as below

Now see the output

The above view page is coming from userNotFound.jsp.

When the user enters invalid credentials, our login controller will throw InvalidUserException and
We have configured the same exception in spring configuration file for the userNotFound.jsp

Now access the below url which actually throws general exception

http://localhost:8080/SimpleMappingExceptionResolver/getGenericException

Just to see how any unhandled exceptions are handled by SimpleMappingExceptionResolver by using the property ‘defaultErrorView’.

see the output

See that , the view page coming here is genericError.jsp

As spring configuration file is defined with Exception resolver and
defaultErrorView is mapped to genericError.jsp, the above view page is displayed.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on