<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">Exception Handling in Spring MVC is about handling exceptions in the application by using spring framework. Spring offers we can customized our error page to more friendly error page to user. This example provides the steps to write your own 404 Resource Not Found error page for your application.</div>
<div dir="ltr"></div>
<div dir="ltr" style="text-align: justify;">Here I am writing a custom exception for 404 error using the <em>HttpStatus.NOT_FOUND</em>. This will be annotated as the exception <em>@ExceptionHandler</em> in the controller. Whenever there is any error thrown on this type, it will be redirected to the configured error page.</div>
<div dir="ltr"></div>
<div dir="ltr" style="text-align: justify;">
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<p>Lets see the example.</p>
<h2><b>1. Controller in Application</b></h2>
<pre class="highlight">package com.doj.spring.web.controller; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.ExceptionHandler; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.servlet.ModelAndView; 
 
import com.doj.spring.web.bean.Student; 
import com.doj.spring.web.exception.StudentNotFoundException; 
 
@Controller 
public class WebController { 
 
 static Map<;String, Student>; map = new HashMap<;String, Student>;(); 
 @RequestMapping("/") 
 public String home(){ 
 Student student = new Student(); 
 student.setFname("Dinesh"); 
 student.setLname("Rajput"); 
 student.setAge("29"); 
 student.setAddress("Noida"); 
 student.setCourse("MS"); 
 map.put("1000", student); 
 return "home"; 
 } 
 
 @RequestMapping("/doj-student-{rollNumber}") 
 public String dojStudentByRollNumber(ModelMap model, @PathVariable(value="rollNumber") String rollNumber){ 
 Student student = map.get(rollNumber); 
 if (student == null) { 
 throw new StudentNotFoundException("Student Not Found", "ERROR:404"); 
 } 
 String name = student.getFname()+" "+student.getLname()+" "+student.getAddress()+" "+student.getCourse(); 
 model.put("name", name); 
 return "home"; 
 } 
 
 @ExceptionHandler(StudentNotFoundException.class) 
 public ModelAndView handleStudentNotFoundException(StudentNotFoundException ex) { 
 Map<;String, StudentNotFoundException>; model = new HashMap<;String, StudentNotFoundException>;(); 
 model.put("exception", ex); 
 return new ModelAndView("student.error.400", model); 
 
 } 
 
 @ExceptionHandler(Exception.class) 
 public ModelAndView handleException(Exception ex) { 
 Map<;String, Exception>; model = new HashMap<;String, Exception>;(); 
 model.put("exception", ex); 
 return new ModelAndView("student.error.500", model); 
 
 } 
} 
 
 
</pre>
<h2><b>2. Add Custom Exception</b></h2>
<pre class="highlight">package com.doj.spring.web.exception; 
 
import org.springframework.http.HttpStatus; 
import org.springframework.web.bind.annotation.ResponseStatus; 
 
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Student Not Found") 
public class StudentNotFoundException extends RuntimeException{ 
 
 /** 
 * 
 */ 
 private static final long serialVersionUID = -2581975292273282583L; 
 
 String errorMessage; 
 
 String errorCode; 
 
 public StudentNotFoundException(String errorMessage, String errorCode) { 
 super(); 
 this.errorMessage = errorMessage; 
 this.errorCode = errorCode; 
 } 
 
 public String getErrorMessage() { 
 return errorMessage; 
 } 
 
 public void setErrorMessage(String errorMessage) { 
 this.errorMessage = errorMessage; 
 } 
 
 public String getErrorCode() { 
 return errorCode; 
 } 
 
 public void setErrorCode(String errorCode) { 
 this.errorCode = errorCode; 
 } 
 
} 
 
</pre>
<h2><b>3. Student Bean Class</b></h2>
<pre class="highlight">package com.doj.spring.web.bean; 
 
 
public class Student { 
 
 String fname; 
 
 String lname; 
 
 String address; 
 
 String course; 
 
 String age; 
 
 public String getFname() { 
 return fname; 
 } 
 public void setFname(String fname) { 
 this.fname = fname; 
 } 
 public String getLname() { 
 return lname; 
 } 
 public void setLname(String lname) { 
 this.lname = lname; 
 } 
 public String getAddress() { 
 return address; 
 } 
 public void setAddress(String address) { 
 this.address = address; 
 } 
 public String getCourse() { 
 return course; 
 } 
 public void setCourse(String course) { 
 this.course = course; 
 } 
 public String getAge() { 
 return age; 
 } 
 public void setAge(String age) { 
 this.age = age; 
 } 
 
} 
 
</pre>
<h2><b>4. Views JSP</b></h2>
<p><b>home.jsp</b><br />
<b><br />
</b> <b>View for Success Page</b><br />
<b><br />
</b></p>
<pre class="highlight"><;h1>;${name} Welcome to DOJ Classes for Spring MVC!!!<;/h1>; 
</pre>
<p><b>Error Page View</b><br />
<b>400.jsp</b></p>
<pre class="highlight"><;h1>;${exception.errorCode} - ${exception.errorMessage} !!!<;/h1>; 
</pre>
<p><b>mainTemplate.jsp</b></p>
<pre class="highlight"><;!DOCTYPE h1 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">; 
<;%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>; 
<;html>; 
 <;head>; 
 <;title>;<;tiles:insertAttribute name="title"/>;<;/title>; 
 <;style>; 
 .error { 
 color: red; font-weight: bold; 
 } 
 <;/style>; 
 <;/head>; 
 <;body style="text-align: center;">; 
 <;div id="header" style="height: 10%;background-color: gray;">;<;tiles:insertAttribute name="header"/>;<;/div>; 
 <;div id="body" style="height: 70%; background-color: aqua;padding-top: 40px;">;<;tiles:insertAttribute name="body"/>;<;/div>; 
 <;div id="footer" style="height: 10%;background-color: gray;">;<;tiles:insertAttribute name="footer"/>;<;/div>; 
 <;/body>; 
<;/html>; 
 
</pre>
<div id="ads-id" align="center"></div>
<h2><b>5. Spring Configurations based on Java Configuration</b><br />
<b><br />
</b></h2>
<pre class="highlight">package com.doj.spring.web.config; 
 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.ViewResolver; 
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 
import org.springframework.web.servlet.view.tiles3.TilesConfigurer; 
import org.springframework.web.servlet.view.tiles3.TilesViewResolver; 
 
@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages={"com.doj.spring.web.controller"}) 
public class SpringWebConfiguration extends WebMvcConfigurerAdapter{ 
 
 @Bean 
 public ViewResolver viewResolver() { 
 return new TilesViewResolver(); 
 } 
 
 @Bean 
 public TilesConfigurer tilesConfigurer() { 
 TilesConfigurer tiles = new TilesConfigurer(); 
 tiles.setDefinitions(new String[] { 
 "/WEB-INF/view/tiles/tiles-def.xml" 
 }); 
 tiles.setCheckRefresh(true); 
 return tiles; 
 } 
 
 //Configure for default static content handling 
 @Override 
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
 configurer.enable(); 
 } 
} 
 
</pre>
<h2><b>6. Deployment Descriptor based on java configuration</b></h2>
<pre class="highlight">package com.doj.spring.web; 
 
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 
 
import com.doj.spring.web.config.SpringWebConfiguration; 
 
//this file is equivalent to web.xml 
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{ 
 
 //Configuration for non web components like services, daos, repos, etc. 
 @Override 
 protected Class<;?>;[] getRootConfigClasses() { 
 return null; 
 } 
 
 //Specifying Spring MVC configuration class "SpringWebConfiguration.class" it equivalent to *-servlet.xml file 
 @Override 
 protected Class<;?>;[] getServletConfigClasses() { 
 return new Class<;?>;[]{SpringWebConfiguration.class}; 
 } 
 
 //Mapping dispatcher server to "/" i.e. Servlet Mapping in the web.xml 
 @Override 
 protected String[] getServletMappings() { 
 return new String[]{"/"}; 
 } 
} 
 
</pre>
<p>All files related this example is not mention here for whole application you can download the zip of working application.</p>
<h2><a href="https://sites.google.com/a/dineshonjava.com/dineshonjava/dineshonjava/SpringMVCExceptionHandlingExample.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>SpringMVCExceptionHandlingExample</b></a></h2>
<h2><b>7. Lets see demo this application</b></h2>
<p><b>1. Welcome Page</b></p>
<p><i><b>http://localhost:8080/SpringMVCExceptionHandlingExample/</b></i></p>
<p> ;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2016/03/welome.png" border="0" /></div>
<p><b>2. Error Page</b></p>
<p><b><i>http://localhost:8080/SpringMVCExceptionHandlingExample/doj-student-10001</i></b></p>
<p> ;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2016/03/welome-1.png" border="0" /></div>
<p> ;</p>
</div>
<p> ;</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Spring MVC Related Posts</b></span></p>
<ul>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><span style="color: red;">Spring MVC Web Tutorial</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-mvc-interview-questions-and-answers/"><span style="color: red;">Spring MVC Interview Questions</span></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-mvc/"><span style="color: red;">MVC Design Pattern</span></a></b></li>
<li><b><a href="https://dineshonjava.com/what-is-dispatcherservlet-in-spring-and-its-uses/"><span style="color: red;">Spring MVC DispatcherServlet </span></a></b></li>
<li><b><a href="https://dineshonjava.com/difference-between-applicationcontext-webapplicationcontext-in-spring-mvc/"><span style="color: red;">Spring MVC WebApplicationContext and Root Application Context</span></a></b></li>
<li><b><a href="https://dineshonjava.com/stereotype-annotations-in-spring/"><span style="color: red;">Spring MVC @Controller Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestmapping-annotation-in-spring-mvc/"><span style="color: red;">Spring MVC @RequestMapping Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestparam-annotation-in-spring-mvc-with-example/"><span style="color: red;">Spring MVC @RequestParam Annotation</span></a></b></li>
<li><b><a href="https://dineshonjava.com/difference-between-applicationcontext-webapplicationcontext-in-spring-mvc/"><span style="color: red;">Spring MVC ContextLoaderListener</span></a></b></li>
<li><b><a href="https://dineshonjava.com/requestparam-vs-pathvariable-annotations-in-spring-mvc/"><span style="color: red;">Spring MVC @RequestParam and @PathVariable annotations</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-30-mvc-hello-world-example/"><span style="color: red;">Spring MVC Hello World Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-exception-handling-example/"><span style="color: red;">Spring MVC Exception Handling Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-mvc-with-hibernate-crud-example/"><span style="color: red;">Spring MVC with Hibernate CRUD Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-tiles-plugin-with-example/"><span style="color: red;">Spring MVC Tiles Plugin with Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-and-interceptor-with/"><span style="color: red;">Spring MVC Interceptor with example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/integration-spring-mvc3-and-mongodb/"><span style="color: red;">Spring MVC with MongoDB CRUD Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-3-mvc-internationalization/"><span style="color: red;">Spring MVC Internationalization &; Localization with Example</span></a></b></li>
</ul>
<p> ;</p>
</div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/exception-handling-in-spring-mvc/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/requestmapping-annotation-in-spring-mvc/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '153'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…