This example presents the basic concept of using in Spring the exception handling.
The technologies used are :
-
– Spring 4.3.18
– JDK 1.80
– Maven 3.3.9
You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :
mvn eclipse:eclipse
Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).
package javaspringexamples.spring.exceptionhandling.domain; /** * * @author mounir.sahrani@gmail.com * */ public class Country { private String name; private String isoCode; public Country() { } public Country(String name, String isoCode) { this.name = name; this.isoCode = isoCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } }
package javaspringexamples.spring.exceptionhandling.exception; /** * * @author mounir.sahrani@gmail.com * */ public class CountryNotFoundException extends Exception { public CountryNotFoundException(String name) { super("Country not found with name: " + name); } }
package javaspringexamples.spring.exceptionhandling.handler; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; /** * * @author mounir.sahrani@gmail.com * */ @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ModelAndView handleException() { return new ModelAndView("errorGlobal"); } }
package javaspringexamples.spring.exceptionhandling.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javaspringexamples.spring.exceptionhandling.domain.Country; import javaspringexamples.spring.exceptionhandling.exception.CountryNotFoundException; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.Map; /** * * @author mounir.sahrani@gmail.com * */ @Controller public class CountryController { private Map<String, Country> countries = new HashMap<String, Country>(); @PostConstruct public void setup() { countries.put("morocco", new Country("Morocco", "MA")); countries.put("france", new Country("France", "FR")); countries.put("united states of america", new Country("United states of America", "US")); countries.put("error", new Country("Error", "Err")); } @RequestMapping(value = "/form") public ModelAndView country() { return new ModelAndView("form", "country", new Country()); } @RequestMapping(value = "/result") public ModelAndView process(String name) throws Exception { ModelAndView modelAndView = new ModelAndView(); if ("error".equalsIgnoreCase(name)) { throw new Exception(); } Country country = countries.get(name.toLowerCase()); if (country == null) { throw new CountryNotFoundException(name); } modelAndView.addObject("country", country); modelAndView.setViewName("result"); return modelAndView; } @ExceptionHandler(CountryNotFoundException.class) public ModelAndView handleException(CountryNotFoundException e) { ModelAndView modelAndView = new ModelAndView("errorCountry"); modelAndView.addObject("errorMessage", e.getMessage()); return modelAndView; } }
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.mvc</url-pattern> </servlet-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="javaspringexamples.spring.exceptionhandling" /> <context:annotation-config /> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
<% response.sendRedirect("form.mvc"); %>
<%@ page contentType="text/html; charset=ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%> <html> <head> <title>JavaSpringExamples Exception Handling</title> </head> <body> <h2>Search Country</h2> <mvc:form modelAttribute="country" action="result.mvc"> <table> <tr> <td><mvc:label path="name">Country Name</mvc:label></td> <td><mvc:input path="name" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Search" /></td> </tr> </table> </mvc:form> </body> </html>
<%@ page contentType="text/html; charset=ISO-8859-1"%> <html> <head> <title>Country Not Found</title> </head> <body> <h2>${errorMessage}</h2> </body> </html>
<html> <head> <title>Error!</title> </head> <body> <h2>Error occurred!</h2> </body> </html>
<%@ page contentType="text/html; charset=ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%> <html> <head> <title>JavaSpringExamples Exception Handling</title> </head> <body> <h2>Search Country</h2> <table> <tr> <td>Country Name :</td> <td>${country.name}</td> </tr> <tr> <td>ISO Code :</td> <td>${country.isoCode}</td> </tr> </table> </body> </html>
Get the sources of the example from the following GitHub url