Spring MVC Exception Handling – ControllerAdvice

Spring MVC

Spring MVC provides several ways of handling exceptions that occurs during the execution of your application. Today we will discuss the use of ControllerAdvice for handling exceptions.

ControllerAdvice annotation is used to handle exceptions that arise/thrown from any of the controller that is defined in the application.

For ControllerAdvice to work , we need to define in the spring confirguration file, else the annotation will not recognized and hence the exception handling will not work.

lets create a small project to test this feature.

1. Create a Home Controller to show the home page and throw few exceptions that can be handled.

2. Create a ExceptionController and annotate with @ControllerAdvice.
In this class add 2 methods that will handle 2 different Exceptions. You can also handle any of your user defined exceptions.

3. Create the home and exception jsp’s

4. The web.xml

5. The dispatcher-servlet.xml

6. Now build the project and run it.

On clicking any if the links on the home page, an exception will be thrown from HomeController.
This exception will be handled by the ErrorController, which adds a message and redirects the page to exception.jsp

Spring MVC Features | Spring MVC Exception Handling - ControllerAdvice

Spring MVC Exception Handling - ControllerAdvice | Spring MVC Features

Download the Source