In this tutorial you will learn about the exception handling in Spring MVC
In this tutorial you will learn about the exception handling in Spring MVCIn any web application it is always recommended to display user friendly custom error page rather than displaying long programming error code. In Servlet you can also map the error page as in the web.xml
<error-page> <error-code>404</error-code> <location>/errorPages/404.jsp</location> </error-page> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/errorPages/404.jsp</location> </error-page>
The above mapped error page will be directly rendered by the servlet container.
The Spring allows you to render more user friendly errors. The following is the way to handle exception in spring.
1. Write a ExceptionHandler class that extends the RuntimeException as
SpringException.java
package roseindia.exception; 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; } }
2. Then map this exception class in dispatcher servlet as
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="roseindia.exception.SpringException"> errorPage </prop> </props> </property> <property name="defaultErrorView" value="error" /> </bean>
Here errorPage is the name of the error page that displays the error
3. Apply your ligic in the controller as
if (registration.getName().length() < 5) { throw new SpringException("Given name is too short"); } else { model.addAttribute("name", registration.getName()); } if (registration.getAge() < 10) { throw new SpringException("Given age is too low"); } else { model.addAttribute("age", registration.getAge()); }
The page which displays the error is as
<%@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>