In this article I shall discuss about how to handle exceptions in Spring. In servlet web applications, exception mappings are defined in the web application descriptor web.xml. In Spring, HandlerExceptionResolver implementations can be used to deal with unexpected exceptions that occur during controller execution. These implementations provide information about which handler was executing when the exception was thrown.
Another way to handle exception is using the org.springframework.web.servlet.handler.SimpleMappingExceptionResolver. This enables you to take the class name of any exception that might be thrown and map it to a view name. Exception handling can also be done using @ExceptionHandler annotation. This can be used on methods that should be invoked to handle an exception. Such methods may be defined locally within an @Controller or may apply globally to all @RequestMapping methods when defined within an @ControllerAdvice class.
also read: follow us on @twitter and @facebook
- Spring Tutorials ( Collection for Spring reference tutorials)
- Spring Framework Interview Questions
- Introduction to Spring LDAP
- How to write Custom Spring Callback Methods?
Exception Handling in Spring – Example
In the example below let’s see how to do the exception handling in Spring MVC using SimpleMappingExceptionResolver and @ExceptionHandler.
Let us have working Eclipse IDE in place and follow steps below to create a Spring application:
Step 1: Create Project
Create a Dynamic Web Project with a name SpringExceptionHandling.
Follow the option File -> New -> Project ->Dynamic Web Project and finally select Dynamic Web Project wizard from the wizard list. Now name your project as SpringExceptionHandling using the wizard window.
Step2: Add external libraries
Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-INF/lib:
- asm-3.1.jar
- commons-logging-1.1.1.jar
- org.springframework.web.servlet-3.2.2.RELEASE.jar
- spring-aop-3.2.2.RELEASE.jar
- spring-aspects-3.2.2.RELEASE.jar
- spring-beans-3.2.2.RELEASE.jar
- spring-context-support-3.2.2.RELEASE.jar
- spring-context-3.2.2.RELEASE.jar
- spring-core-3.2.2.RELEASE.jar
- spring-expression-3.2.2.RELEASE.jar
- spring-webmvc-3.2.2.RELEASE.jar
- spring-web-3.2.2.RELEASE.jar
Step3: Create bean and Controller and exception classes
Create the package com.javabeat under src folder. (Right click on src -> New -> Package ->)
Create the bean file Product and Controller ProductController usnder the package com.javabeat.
Contents of Product are as follows:
package com.javabeat; public class Product { private String name; private Integer id; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
Contents of ProductController are as follows:
package com.javabeat; 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 ProductController { @RequestMapping(value = "/product", method = RequestMethod.GET) public ModelAndView product() { return new ModelAndView("product", "command", new Product()); } @RequestMapping(value = "/addProduct", method = RequestMethod.POST) @ExceptionHandler(ExampleException.class) public String addProduct(@ModelAttribute("HelloWeb") Product product, ModelMap model) { if (product.getName().length() < 5) { throw new ExampleException("Product Name entered is too short"); } else { model.addAttribute("name", product.getName()); } return "result"; } }
Contents of ExampleException are as follows:
package com.javabeat; public class ExampleException extends RuntimeException { private String exceptionMsg; public ExampleException(String exceptionMsg) { this.exceptionMsg = exceptionMsg; } public String getExceptionMsg() { return exceptionMsg; } public void setExceptionMsg(String exceptionMsg) { this.exceptionMsg = exceptionMsg; } }
Step4: Create view files
Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create view files product.jsp, result.jsp, error.jsp, and ExceptionPage.jsp under jsp sub-folder. Contents of >product.jsp are
<%@ 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"> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring MVC Exception Handling</title> </head> <body> <h2>Product Information</h2> <form:form method="POST" action="/HelloWeb/addProduct"> <table> <tr> <td><form:label path="name">Name</form:label></td> <td><form:input path="name" /></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>
Contents of result.jsp are
<%@ 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"> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring MVC Form Handling</title> </head> <body> <h2>Product Information Saved</h2> <table> <tr> <td>Name</td> <td>${name}</td> </tr> <tr> <td>ID</td> <td>${id}</td> </tr> </table> </body> </html>
Conetents of error.jsp are
<%@ 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>Spring Error Page</title> </head> <body> <p>OOps an error occurred!!!!!!.</p> </body> </html>
Contents of ExceptionPage.jsp are
<%@ 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>Spring Exception Handling</title> </head> <body> <h2>Spring Exception Handling</h2> <h3>${exception.exceptionMsg}</h3> </body> </html>
Step5: Create configuration files
Create tge configuration files web.xml and HelloWeb-servlet.xml. under the the directory WEB-INF. The contents of web.xml are:
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Spring Exception Handling</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
The contents of HelloWeb-servlet.xml are:
<?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.javabeat" /> <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.javabeat.ExampleException"> ExceptionPage </prop> </props> </property> <property name="defaultErrorView" value="error"/> </bean> </beans>
Step6: Deploy and execute
Once all the files are ready export the 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 the Tomcat server and try to access the URL http://localhost:8080/HelloWeb/product. You should see the following scree
You should see the below page once you submit the above data:
Summary
In this artcile we saw exception handling in Spring using SimpleMappingExceptionResolver and @ExceptionHandler.In the next artcile I shall dis cuss about using themes in Spring.If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook