Spring - Exception Handling Example

The following example shows how to write a simple web-based application using Spring MVC Framework, which can handle one or more exceptions raised inside its controllers. To start with, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework −

Step

Description

1

Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project.

2

Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-INF/lib.

3

Create a Java classes Student, StudentController and SpringException under the com.tutorialspoint package.

Following is the content of StudentController.java file. Here, you need to annotate a service method using @ExceptionHandler where you can specify one or more exceptions to be handled. If you are specifying more than one exception then you can use comma separated values.

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEB-INF/lib folder.

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

Once you are done creating the source and configuration files, export your application. Right-click on your application and use the Export > WAR File option and save yourHelloWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try to access the URL http://localhost:8080/HelloWeb/student. If everything is fine with your Spring Web Applicationand, you should see the following result.

Enter the values as shown above and click the Submit buttom. If everything is fine with your Spring Web Application, you should see the following result.