Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC - Exception Handling
Next article icon

Spring MVC - Exception Handling

Last Updated : 11 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: Spring MVC

When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception. In this article we'll Spring Mvc project to show how to intercept and define exceptions, we'll look at how to define method level as well as the class level exception.

Steps to Create the Application

First, create a maven project, we are using Eclipse IDE for this project. Now, search for webapp, as we are creating a web application. Choose to create maven while creating a new project and add a maven webapp archetype. Enter the group id and the artifact id for your project and click finish.

After clicking finish your project structure would look something like this:

The pom.xml is auto-created with any maven project, it defines all the dependencies required for the project. Make sure to add all the dependencies mentioned in this file.

XML
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd">   <modelVersion>4.0.0</modelVersion>    <groupId>com.gfg</groupId>   <artifactId>SpringMvcExceptionHandling</artifactId>   <version>0.0.1-SNAPSHOT</version>   <packaging>war</packaging>    <name>SpringMvcExceptionHandling Maven Webapp</name>   <!-- FIXME change it to the project's website -->   <url>http://www.example.com</url>    <properties>     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>     <maven.compiler.source>1.7</maven.compiler.source>     <maven.compiler.target>1.7</maven.compiler.target>   </properties>    <dependencies>     <dependency>       <groupId>junit</groupId>       <artifactId>junit</artifactId>       <version>4.11</version>       <scope>test</scope>     </dependency>     <dependency>           <groupId>org.springframework</groupId>           <artifactId>spring-webmvc</artifactId>           <version>5.1.1.RELEASE</version>       </dependency>       <dependency>           <groupId>org.apache.tomcat</groupId>           <artifactId>tomcat-jasper</artifactId>           <version>9.0.12</version>       </dependency>       <dependency>             <groupId>javax.servlet</groupId>             <artifactId>servlet-api</artifactId>             <version>3.0-alpha-1</version>         </dependency>       <dependency>           <groupId>javax.servlet</groupId>           <artifactId>jstl</artifactId>           <version>1.2</version>       </dependency>     </dependencies>    <build>     <finalName>SpringMvcExceptionHandling</finalName>     <pluginManagement>       <plugins>         <plugin>           <artifactId>maven-clean-plugin</artifactId>           <version>3.1.0</version>         </plugin>         <plugin>           <artifactId>maven-resources-plugin</artifactId>           <version>3.0.2</version>         </plugin>         <plugin>           <artifactId>maven-compiler-plugin</artifactId>           <version>3.8.0</version>         </plugin>         <plugin>           <artifactId>maven-surefire-plugin</artifactId>           <version>2.22.1</version>         </plugin>         <plugin>           <artifactId>maven-war-plugin</artifactId>           <version>3.2.2</version>         </plugin>         <plugin>           <artifactId>maven-install-plugin</artifactId>           <version>2.5.2</version>         </plugin>         <plugin>           <artifactId>maven-deploy-plugin</artifactId>           <version>2.8.2</version>         </plugin>       </plugins>     </pluginManagement>   </build> </project> 

The web.xml defines mapping with different URLs and servlets to handle requests for those URLs. 

XML
<web-app xmlns="http://java.sun.com/xml/ns/javaee"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"     version="3.0">          <servlet>         <servlet-name>gfg</servlet-name>         <servlet-class>             org.springframework.web.servlet.DispatcherServlet         </servlet-class>         <init-param>             <param-name>contextConfigLocation</param-name>             <param-value>/WEB-INF/gfg-servlet.xml</param-value>         </init-param>         <load-on-startup>1</load-on-startup>     </servlet>      <servlet-mapping>         <servlet-name>gfg</servlet-name>         <url-pattern>/</url-pattern>     </servlet-mapping> </web-app> 

  

The gfg-servlet.xml file handles all HTTP requests for the web applications. The component scan locates and allocated beans according to the defined annotation. The annotation-driven enable the spring annotation classes. The bean configuration helps in identifying and scanning the JSP located in the views folder. 


 

XML
<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:context="http://www.springframework.org/schema/context"     xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans                          http://www.springframework.org/schema/beans/spring-beans.xsd                         http://www.springframework.org/schema/mvc                          http://www.springframework.org/schema/mvc/spring-mvc.xsd                         http://www.springframework.org/schema/context \                         http://www.springframework.org/schema/context/spring-context.xsd">      <context:component-scan base-package="com.gfg" />      <bean         class="org.springframework.web.servlet.view.InternalResourceViewResolver">         <property name="prefix">             <value>/WEB-INF/views/</value>         </property>         <property name="suffix">             <value>.jsp</value>         </property>     </bean>     <mvc:annotation-driven />      </beans> 

  

The Student class in the com.gfg.model defines the student object with three objects firstName, lastName, and rollNo. Notice that we have kept the roll number as a string instead of an integer, this will help us to check for possible NumberFormat exceptions.


 

Java
package com.gfg.model;  public class Student {      private String firstName;     private String lastName;     private String rollNo;      public Student(String firstName, String lastName,                    String rollNo)     {         super();         this.firstName = firstName;         this.lastName = lastName;         this.rollNo = rollNo;     }      public Student() {}      public String getFirstName() { return firstName; }      public void setFirstName(String firstName)     {         this.firstName = firstName;     }      public String getLastName() { return lastName; }      public void setLastName(String lastName)     {         this.lastName = lastName;     }      public String getRollNo() { return rollNo; }      public void setRollNo(String rollNo)     {         this.rollNo = rollNo;     } } 

  

The LoginController class in the com.gfg.controller package defines two methods, the showForm method defines a Get mapping and simply shows the student login form. The processForm method has two parameters of @ModelAttribute for students and a Model to set attributes in our view pages. The model parameter sets all the attributes to the view page. Remember, in the Student class we defined rollNo as a String. Now, we will parse it into int: this will help in catching two NumberFormat exceptions. If the string is empty or the string has alphabets for both it will send a NumberFormatException. Now, to catch that exception and handle it separately for better user experience we define a method numberformatHandler and annotate it with the @ExceptionHandler, and set the value to NumberFormatException.class. So, this was a way to handle Exception at the method level.


 

Java
package com.gfg.controller;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping;  import com.gfg.model.Student;  @Controller public class LoginController {          @RequestMapping("/login")     public String showForm(Model theModel) {         theModel.addAttribute("student", new Student());         return "portal";     }          @RequestMapping("/welcome")     public String processForm(@ModelAttribute("welcome") Student student, Model mod) {             mod.addAttribute("FirstName", student.getFirstName());         mod.addAttribute("LastName", student.getLastName());                 int n = Integer.parseInt(student.getRollNo());         mod.addAttribute("RollNo", n);             return "welcome";     }            @ExceptionHandler(value = NumberFormatException.class)     public String numberformatHandler(Model theModel) {                 theModel.addAttribute("err", "NumberFormatException");         return "error";     } } 

The  MyExceptionHandler class in the com.gfg.errorhandler defines all the exceptions for our application so that for a different kind of exception the user sees a proper and simple error page. To make it available for all the classes in our project we just have to add the annotation @ControllerAdvice, this will advise spring MVC to use our exception method instead of server-generated pages. So, In this we have defines an Exception Handler at the class level.

Java
package com.gfg.errorhandler;  import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler;  @ControllerAdvice public class MyExceptionHandler {          @ExceptionHandler(value = NullPointerException.class)     public String nullPointerHandler(Model theModel) {         theModel.addAttribute("err", "NullPointerException");         return "error";     }          @ExceptionHandler(value = Exception.class)     public String AnyOtherHandler() {         return "error";     }      } 

The portal.jsp file in the views folder defines the Student login portal. 

HTML
<%@ taglib prefix="form" url="http://www.springframework.org/tags/form" %>     <html>   <head>   </head>   <body>       <h1>Student Portal</h1>     <form:form action="welcome" modelAttribute="student">          <label>First name:</label>          <form:input path="firstName" />         <br><br>                     <label>Last name:</label>           <form:input path="lastName" />           <br><br>                       <label>Roll No:</label>           <form:input path="rollNo" />           <br><br>                   <input type="submit" value="Submit" />              </form:form>   </body>   </html>   

The welcome.jsp page in the views folder defines the welcome page for our application.

HTML
<%@ taglib prefix="form" url="http://www.springframework.org/tags/form" %>     <html>   <head>   </head>   <body>       <h1>Student Portal</h1>     <form:form action="welcome" modelAttribute="student">          <label>First name:</label>          <form:input path="firstName" />         <br><br>                     <label>Last name:</label>           <form:input path="lastName" />           <br><br>                       <label>Roll No:</label>           <form:input path="rollNo" />           <br><br>                   <input type="submit" value="Submit" />              </form:form>   </body>   </html>   

The error.jsp page is a simple exception handler page that defines the name of the exception and informs the user about an exception.

HTML
<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body>     <h1>Opps....</h1>      <h1> ${err} Exception caused</h1> </body> </html> 

  

After adding all the classes and configuration files your project would look something like this:


 


 

Now that we have completed our project, it's time to run it on a tomcat server, just start the tomcat server and type http:localhost:8080/SpringMvcExceptionHandling/login


 

OutputOutputOutputOutputOutput


 

So, in this Spring MVC project, we defined exception handlers at the method as well as at class level and defined our own custom exception view page for better user experience.


 


Next Article
Spring MVC - Exception Handling

A

ashutosh44
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Spring MVC Tutorial
    In this tutorial, we'll cover the fundamentals of Spring MVC, including setting up your development environment, understanding the MVC architecture, handling requests and responses, managing forms, and integrating with databases. You'll learn how to create dynamic web pages, handle user input, and i
    7 min read
    Spring - MVC Framework
    The Spring MVC Framework follows the Model-View-Controller architectural design pattern, which works around the Front Controller, i.e., the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapp
    4 min read
    Spring MVC using Java Based Configuration
    Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles application integration. This enables the developer to create complex applications using plain Java classes. The model object can be passed between the view and the controller using map
    3 min read
    ViewResolver in Spring MVC
    Spring MVC is a powerful Web MVC Framework for building web applications. It provides a structured way to develop web applications by separating concerns into Model, View, and Controller. One of the key features of Spring MVC is the ViewResolver, which enables you to render models in the browser wit
    7 min read
    How to Create Your First Model in Spring MVC?
    Spring MVC is a powerful Web MVC framework for building web applications. It is designed around the Model-View-Controller (MVC) pattern, which separates the application into three main components:Model: Represents the data of the application. It can be a single object or a collection of objects.View
    6 min read
    How to Create Your First View in Spring MVC?
    Spring MVC is a powerful Web MVC Framework for building web applications. It is designed around the Model-View-Controller (MVC) pattern, which separates the application into three main components:Model: Represents the data of the application. It can be a single object or a collection of objects.View
    5 min read
    Spring MVC CRUD with Example
    In this article, we will explore how to build a Spring MVC CRUD application from scratch. CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a popular framework for building web applications. Spring MVC follows
    7 min read
    Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
    Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain Java classes. The model object can be passed between the view and the controller
    5 min read
    What is Dispatcher Servlet in Spring?
    Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made
    6 min read
    Spring - Shortcut to Create Dispatcher Servlet in Eclipse/Spring Tool Suite
    Eclipse is an Integrated Development Environment (IDE) used in computer programming. It includes a base workspace and an extensible plug-in system for customizing the environment. It is the second-most-popular IDE for Java development. Eclipse is written mostly in Java and its primary use is for dev
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences