Tip: Parent controller to handle exception in Spring MVC

Spring MVC is a powerful framework and I got a tip that can be useful. Spring MVC uses the technique of something called Controller which can be bound to handle the different user request to do a prerequisites before showing the user a specific page he requested.
In case you got many controllers and you need to handle the common exceptions for your application. You can do that by making a parent class which I prefer to call Parent Controller that can handle the exception as the bellow examples shows. Then you can extend that class in your other different controllers.
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

public class ParentController {

 private ModelAndView modelAndView;
 public ModelAndView handleNullPointerException(NullPointerException e) {
  // Display the error page
  modelAndView = new ModelAndView("404");
  modelAndView.addObject("message", "NullPointerException occured - " + System.currentTimeMillis());
  return modelAndView;


Popular posts from this blog

JavaOne 2015 Session: EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples by Gohar

Spring Core - Different Types of Bean Injection

PrimeFaces Push with Atmosphere