Spring MVC exception handling tutorial

Spring mvc framework provides the facility to build flexible and loosely coupled web applications. MVC stands for Model-View-Controller design pattern which separates the business logic, presentation logic and navigation logic. Let us discuss in eclipse.

Example Explanation:

Use http://localhost:8080/SpringMVCExample6/ student url to start the application. A request for respective resource will generate. Request will be handled by DispatcherServlet. It delegates the request to the ExceptionHandlingController controller. The LoginController controller resolve the request with help of RequestMapping annotation, executes the specific functionality and returns the ModelAndView object to the DispatcherServlet. The DispatcherServlet then take the help of InternalResourceViewResolver to get the actual view name. In our example it will return the “/WEB-INF/jsp/student.jsp. The DispatcherServlet then insert the model data into view and render response. Same request response cycle will execute when we click on submit button after entering the student details.

Note: The @ExceptionHandler annotation is used to specify the exception handlers. Use comma separated handlers if more than one exceptions are specified.

Example:

student.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
  <head>
    <title>Spring MVC exception handling example.</title>
  </head>
 
  <body>
<form:form method="POST" action="/SpringMVCExample6/addStudent">
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td><form:label path="className">Class</form:label></td>
        <td><form:input path="className" /></td>
    </tr>
    <tr>
        <td><form:label path="rollNo">RollNo</form:label></td>
        <td><form:input path="rollNo" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4"
   xmlns="http://java.sun.com/xml/ns/j2ee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
   <servlet>
      <servlet-name>ExceptionHandling</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
 
   <servlet-mapping>
      <servlet-name>ExceptionHandling</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
 
</web-app>

ExceptionHandling-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
   <context:component-scan base-package="com.javawithease.business" />
 
  <bean class=
   "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>
 
  <bean class=
   "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
   <property name="exceptionMappings">
      <props>
         <prop key="com.javawithease.business.SpringException">
            exceptionpage
         </prop>
      </props>
   </property>
   <property name="defaultErrorView" value="error"/>
  </bean>
</beans>

Student.java

public class Student {
	private String name;
	private String className;
	private String rollNo;
 
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
 
}

SpringException.java

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;
   }
}

ExceptionHandlingController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
 
@Controller
public class ExceptionHandlingController {
   @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("SpringWeb")Student student, 
   ModelMap model) {
      if(student.getName().length() < 5 ){
         throw new SpringException("Student name should " +
         		"contain atleast 5 characters.");
      }else{
    	  model.addAttribute("name", student.getName());
      }
 
      model.addAttribute("className", student.getClassName());     
      model.addAttribute("rollNo", student.getRollNo());
 
      return "welcome";
   }
}

welcome.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Spring MVC exception handling example.</title>
  </head>
  <body>
    <h2>Student Details</h2>
    <table>
    <tr>
        <td>Name</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>Class</td>
        <td>${className}</td>
    </tr>
    <tr>
        <td>RollNo</td>
        <td>${rollNo}</td>
    </tr>
   </table>  
  </body>
</html>

exceptionpage.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Spring MVC exception handling example.</title>
  </head>
  <body>
   <h3>${exception.exceptionMsg}</h3>
  </body>
</html>

error.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Spring MVC exception handling example.</title>
  </head>
  <body>
   <h3>Unknown exception.</h3>
  </body>
</html>

Output:

Spring example6-1
Enter username with < 5 characters.
Spring example6-2
Click on Submit button.
Spring example6-3
 
Download this example.