Home Tutorial Spring Spring3 Web Spring Exception Handling


Share on Google+Share on Google+
Spring Exception Handling
Posted on: August 30, 2012 at 12:00 AM
In this tutorial you will learn about the exception handling in Spring MVC

Spring Exception Handling

In 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



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


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">
			<prop key="roseindia.exception.SpringException">
	<property name="defaultErrorView" value="error" />

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"%>
<title>Spring MVC Exception Handling</title>

<h2>Spring MVC Exception Handling</h2>



Download Complete Application


Related Tags for Spring Exception Handling:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 30, 2012

Recommend the tutorial

Advertisements Advertisements