• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring MVC Custom Exception Handling

December 8, 2014 by javainterviewpoint Leave a Comment

We have learnt how to handle exception using the Spring exception handling mechanism through my previous articles and we know how the @ControllerAdvice and @ExceptionHandler annotations works, how to handle exception globally. Now let’s see how do we handle a User Defined Exception.

Folder Structure :

  1. Create a Dynamic Web Project RegistrationForm and create a package for our src files “com.javainterviewpoint“
  2. Place the Spring 3 jar files under WEB-INF/Lib 

    commons-logging-1.1.1.jar
    log4j-1.2.16.jar
    slf4j-api-1.7.5.jar
    slf4j-log4j12-1.7.5.jar
    spring-aspects-3.2.4.RELEASE.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar

  3. Put the index.jsp under the WebContent directory.
  4. Create the Java classes RegistrationController.java, GlobalException.java, UserDefinedException.java and RegistrationBean.java under  com.javainterviewpoint folder.
  5. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  6. View files RegistrationForm.jsp and exceptionPage.jsp are put under the sub directory under WEB-INF/Jsp

UserDefinedException.java

package com.javainterviewpoint;

public class CustomException extends RuntimeException
{
	String message;
	String name;
	
	public CustomException(String message,String name)
	{
		this.message=message;
		this.name=name;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getName() {
		return name;
	}

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

Create our own UserDefinedException class which extends RuntimeException, with two attributes such as name and message. So that we can pass the Custom name and Custom message which can be used to display to the user.

GlobalException.java

package com.javainterviewpoint;

import java.io.IOException;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalException 
{
	@ExceptionHandler(IOException.class)
	public ModelAndView  processIOException(IOException ioe)
	{
		ModelAndView mav = new ModelAndView("exceptionPage");
		 mav.addObject("name", ioe.getClass().getSimpleName());
	     mav.addObject("message", ioe.getMessage());
	 
	     return mav;
	}
	@ExceptionHandler(UserDefinedException.class)
	public ModelAndView  processCustomException(UserDefinedException ud)
	{
		ModelAndView mav = new ModelAndView("exceptionPage");
		 mav.addObject("name", ud.getName());
	     mav.addObject("message", ud.getMessage());
	 
	     return mav;
	}	
}

Here the processCustomException() will handle the UserDefinedException when occurred, it will also redirect the user to the exceptionPage.

RegistrationController.java

package com.javainterviewpoint;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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 RegistrationController 
{
	@ModelAttribute("professionList")
	public List populateProfessionList()
	{
		List professionList = new ArrayList(); 
		professionList.add("Devloper");
		professionList.add("Manager");
		professionList.add("Architecht");
		
		return professionList;
	}
	@ModelAttribute("hobbyList")
	public List populateHobbyList()
	{
		List hobbyList = new ArrayList(); 
		hobbyList.add("Cricket");
		hobbyList.add("Football");
		hobbyList.add("Hockey");
		hobbyList.add("Basketball");
		
		return hobbyList;
	}
	@RequestMapping("/dispForm")
	public String displayForm(Map model)
	{
		RegistrationBean rb = new RegistrationBean();
		model.put("rb",rb);
		return "registrationForm";
	}
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String processRegistration(@ModelAttribute("rb") RegistrationBean rb) throws IOException
	{
		if(rb.getFirstName().length()>5)
		{
			throw new IOException("IOException has occured");
		}
		if(rb.getLastName().length()>5)
		{
			throw new UserDefinedException("Custom Exception has occured", "CustomException");
		}
		return "success";
	}
}

Our RegistrationController class will throw two exceptions
1. When the firstName is greater than 5 it will throw IOException
2. When the lastName is greater than 5 it will throw CustomException
Both the exceptions will be handled globally by our GlobalException class.

exceptionPage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h3 style="color: red">Ops!! Something went wrong!</h3>
 <h5 style="color: red">${name}</h5><br>
 <h5 style="color: red">${message}</h5>
</body>
</html>

This page will be rendered to the user when exception occurs.

Index.jsp

This is simply a start-up page which redirects the user to our RegistrationForm.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <a href="displayForm.html">Click here to Register</a>
</body>
</html>

RegistrationForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 
 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<body>
 <form:form action="register" method="post" commandName="rb">
 <table>
 <tr><td>First Name</td><td><form:input path="firstName"/></td></tr>
 <tr><td>Last Name</td><td><form:input path="lastName"/></td></tr>
 <tr><td>Email</td><td><form:input path="email"/></td></tr>
 <tr><td>Profession</td><td><form:select path="profession" items="${professionList}"></form:select></td><td></td></tr>
 <tr><td>Hobby</td><td><form:checkboxes items="${hobbyList}" path="hobby"/></td></tr>
 <tr><td></td><td><input type="submit" value="Register"></td></tr>
 </table>
 </form:form>
 </body>
</html>

RegistraionBean.java

package com.javainterviewpoint;

public class RegistrationBean 
{
	
	String firstName;
	String lastName;
	String email;
	String profession;
	String[] hobby;
		
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getProfession() {
		return profession;
	}
	public void setProfession(String profession) {
		this.profession = profession;
	}
	public String[] getHobby() {
		return hobby;
	}
	public void setHobby(String[] hobby) {
		this.hobby = hobby;
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 

 <servlet>
 <servlet-name>SpringConfig</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>SpringConfig</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

Spring Configuration File

 <beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
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
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
 <context:component-scan base-package="com.javainterviewpoint"></context:component-scan>
 <mvc:annotation-driven/>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/Jsp/"></property>
 <property name="suffix" value=".jsp"></property>
 </bean>
 
 </beans>

Let’s Run our application

Enter any value in the firstName or lastName field greater than 5 character length and submit the form.

http://localhost:8080/Spring_MVC_ExceptionHandler/

Spring_MVC_Custom_Exception_Handling

Spring_MVC_Custom_ExceptionSpring_MVC_Custom_Exception

Other interesting articles which you may like …

  • Spring MVC Custom Exception Handling
  • Spring MVC Textbox Example
  • Spring MVC Password Example
  • Spring MVC Dropdown Box Example
  • Spring MVC Checkbox And Checkboxes Example
  • Spring MVC Radiobutton And Radiobuttons Example
  • Spring MVC TextArea Example
  • Spring MVC HiddenValue Example
  • context:annotation-config vs context:component-scan
  • Spring MVC BeanNameUrlHandlerMapping Example
  • Spring MVC ControllerClassNameHandlerMapping Example
  • Spring MVC SimpleUrlHandlerMapping Example
  • Spring MVC Flow Diagram
  • Spring MVC Multiple submit buttons in a single form
  • Spring MVC SimpleFormController Example

Filed Under: J2EE, Java, Spring, Spring MVC, Spring Tutorial Tagged With: @ControllerAdvice, @ExceptionHandler, Custom Exception Handling, Exception Handling, Global Exception, Global Exception Handler, Global Handler, RuntimeException, Spring 3.2, Spring Exception, Spring Exception Handler, Spring MVC, Spring MVC Exception Handling

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·