About Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.

Spring MVC Exception Handling Example

This is an example of how to handle exceptions in Spring MVC. In Spring MVC Framework exceptions may occur when a controller is invoked. These exceptions may be handled either with the help of SimpleMappingExceptionResolver class, or with the @ExceptionHandler annotation.

SimpleMappingExceptionResolver is a HandlerExceptionResolver implementation for mapping exception class names to view names, either for a set of given handlers or for all handlers in the DispatcherPortlet. It is set and defined in the container xml configuration file. On the other hand, when xml configuration needs to be avoided, the @ExceptionHandler annotation can be used on Controller methods that will thus be invoked to handle the exception.

Below you can check on how to implement both ways. We will create a simple project with two Controller classes, each one for a case. We will also create a custom Exception class to be used as the exception to handle, and an error page that will be the view part of our MVC project example.

Want to master Spring Framework ?

Subscribe to our newsletter and download the Spring Framework Cookbook right now!

In order to help you master the leading and innovative Java framework, we have compiled a kick-ass guide with all its major features and use cases! Besides studying them online you may download the eBook in PDF format!

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.

Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes", the “Archetype artifact Id” variable to "maven-archetype-webapp" and the “Archetype Version” to "1.0". Click on “OK” to continue.

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Set the “Package” variable to "war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

The Maven project structure is shown below:

It consists of the following folders:

/src/main/java folder, that contains source files for the dynamic content of the application,

the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring-MVC dependencies

Add the dependencies in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc package. We also add the jstl package, since we will make use of it in the view part.

3. Configure the application

The files that we must configure in the application are the web.xml file and the mvc-dispatcher-servlet.xml file.

The web.xml file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/ directory of the application. The <servlet> element declares the DispatcherServlet. When the DispatcherServlet is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in /WEB-INF/ directory. So, we have created the mvc-dispatcher-servlet.xml file, that will be explained below. The <servlet-mapping> element of web.xml file specifies what URLs will be handled by the DispatcherServlet.

The mvc-dispatcher-servlet.xml file is also placed in WebContent/WEB-INF directory. The org.springframework.web.servlet.view.InternalResourceViewResolver bean is used as internal resource views resolver, meaning that it will find the jsp and html files in the WebContent/WEB-INF/ folder. We can also set properties such as prefix or suffix to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers, will be placed and defined, as shown below:

5. SimpleMappingExceptionResolver case

In this case a simple controller is created that throws an exception when invoked. Its configuration will be shown in mvc-dispatcher-servlet.xml file below. FirstController.java class extends the org.springframework.web.servlet.mvc.AbstractController and overrides its handleRequestInternal(HttpServletRequest request, HttpServletResponse response) method, where the exception is thrown.

CustomException.java class is the exception that will be thrown in both cases. Note that the same steps can be followed in the controllers when we need to handle all types of Java exceptions, such as java.lang.Exception.

6. @ExceptionHandler case

The second controller makes use of the @ExceptionHandler annotation. SecondController.java class is an @Controller annotated class, thus declaring that it is a Controller. It has a method, second(), annotated with the @RequestMapping annotation. This annotation maps a URL to either an entire class or a particular handler method. This method also throws a CustomException.

In this case the exception is handled by the @ExecptionHandler annotation, which is set in the handleCustomException(CustomException ex) method. This method returns the error view created above, making use of the org.springframework.web.servlet.ModelAndView class.SecondController.java

7. Configure mvc-dispatcher-servlet.xml file

The mvc-dispatcher-servlet.xml file must be enriched with configuration concerning both controllers.
For the first controller, the org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping is used, which is defined as a bean. It is used to map any URL requests that start with first or first* to the FirstController.java class. The first controller is also defined as a bean here.

The important bean to define and configure for the first controller is the org.springframework.web.servlet.handler.SimpleMappingExceptionResolver bean. It has a property named exceptionMappings. Its value is a key-value pair, consisting of the CustomException class declaration and the error.jsp page declaration. This is where the mapping of the exception and the view is configured for the first controller.

For the second controller, the context:component-scan base-package tag is used, so that the container will scan the base package declared to search for the annotated class. The mvc:annotation-driven tag is also used, to declare explicit support for annotations in the controller.

Leave a Reply

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Receive Java & Developer job alerts in your Area

Leave this field empty if you're human:

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.