Custom 404 Error Page in Spring MVC

Points To Remember

  1. You need to first add the errors in the web.xml and redirect them to a url.
  2. Then you need to map these url to controller to handle them and take necessary actions. 
  3. You can either handle exceptions in your controllers as explained in the link.

Custom Error Pages

Here in this example we are going to create custom error pages in our spring mvc application. So will first of all configure the error codes in web.xml like the following.

web.xml
 <error-page>
  <error-code>400</error-code>
  <location>/400</location>
 </error-page>
 
 <error-page>
  <error-code>404</error-code>
  <location>/404</location>
 </error-page>
 
 <error-page>
  <error-code>500</error-code>
  <location>/500.jsp</location>
 </error-page>
Now when we have configured the error codes and mapped then with the respective url's, we will now create a Controller that will map these error code url's like the following.

HTTPErrorHandler.java
package com.ekiras.util;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HTTPErrorHandler{

 String path = "/error";
 
 @RequestMapping(value="/400")
 public String error400(){
  System.out.println("custom error handler");
  return path+"/400";
 }
 
 @RequestMapping(value="/404")
 public String error404(){
  System.out.println("custom error handler");
  return path+"/404";
 }
 
 @RequestMapping(value="/500")
 public String error500(){
  System.out.println("custom error handler");
  return path+"/500";
 }
 
 
}
So now our Controller will handle the error code url's and will redirect them to the custom error page url's.

No comments :

Post a Comment