Spring MVC - Exception Handling Example



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

Step Description
1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World Example chapter.
2 Create a Java classes Student, StudentController and SpringException under the com.tutorialspoint package.
3 Create a view files student.jsp, result.jsp, error.jsp, and ExceptionPage.jsp under jsp sub-folder.
4 The final step is to create the content of all the source and configuration files and export the application as explained below.

Student.java

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }

   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

SpringException.java

package com.tutorialspoint;

public class SpringException extends RuntimeException{
   private String exceptionMsg;
   
   public SpringException(String exceptionMsg) {
      this.exceptionMsg = exceptionMsg;
   }
   
   public String getExceptionMsg(){
      return this.exceptionMsg;
   }
   
   public void setExceptionMsg(String exceptionMsg) {
      this.exceptionMsg = exceptionMsg;
   }
}

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 exceptions then you can use comma separated values.

StudentController.java

package com.tutorialspoint;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;

@Controller
public class StudentController {

   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   @ExceptionHandler({SpringException.class})
   public String addStudent( @ModelAttribute("HelloWeb")Student student, 
      ModelMap model) {

      if(student.getName().length() < 5 ){
         throw new SpringException("Given name is too short");
      }else{
       model.addAttribute("name", student.getName());
      }
      
      if( student.getAge() < 10 ){
         throw new SpringException("Given age is too low");
      }else{
       model.addAttribute("age", student.getAge());
      }
      model.addAttribute("id", student.getId());
      return "result";
   }
}

Here you specified ExceptionPage as an exception view in case SpringException occurs, if there is any other type of exception then a generic view error will take place.

student.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
   <head>
      <title>Spring MVC Exception Handling</title>
   </head>
   <body>

      <h2>Student Information</h2>
      <form:form method="POST" action="/HelloWeb/addStudent">
         <table>
            <tr>
               <td><form:label path="name">Name</form:label></td>
               <td><form:input path="name" /></td>
            </tr>
            <tr>
               <td><form:label path="age">Age</form:label></td>
               <td><form:input path="age" /></td>
            </tr>
            <tr>
               <td><form:label path="id">id</form:label></td>
               <td><form:input path="id" /></td>
            </tr>
            <tr>
               <td colspan="2">
               <input type="submit" value="Submit"/></td>
            </tr>
         </table>  
      </form:form>
   </body>
</html>

error.jsp

<html>
   <head>
      <title>Spring Error Page</title>
   </head>
   <body>

      <p>An error occured, please contact webmaster.</p>

   </body>
</html>;

Following is the content of Spring view file ExceptionPage.jsp. Here you will access the exception instance via ${exception}.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
   <head>
      <title>Spring MVC Exception Handling</title>
   </head>
   <body>

      <h2>Spring MVC Exception Handling</h2>

      <h3>${exception.exceptionMsg}</h3>

   </body>
</html>

result.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <body>

      <h2>Submitted Student Information</h2>
      <table>
         <tr>
            <td>Name</td>
            <td>${name}</td>
         </tr>
         <tr>
            <td>Age</td>
            <td>${age}</td>
         </tr>
         <tr>
            <td>ID</td>
            <td>${id}</td>
         </tr>
      </table>  
   </body>
</html>

Once you are done with creating source and configuration files, export your application. Right click on your application and use Export > WAR File option and save your HelloWeb.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 :

Spring Student Form

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

Spring Exception Result
Advertisements