@ControllerAdvice is a specialization of @Component which can be used to define methods with @ExceptionHandler, @InitBinder, and @ModelAttribute. By using in @ControllerAdvice class, these methods can be applied to all @RequestMapping methods across multiple @Controller classes instead of just local @Controller class.
In this example we are going to demonstrate the use of @ControllerAdvice with @ExceptionHandler.
Creating controllers
@Controller
public class ExampleController1 {
@RequestMapping("/test1")
public String handleRequest1 () throws Exception {
String msg = String.format("Test exception from class: %s",
this.getClass().getSimpleName());
throw new Exception(msg);
}
}
@Controller
public class ExampleController2 {
@RequestMapping("/test2")
public String handleRequest2 () throws Exception {
String msg = String.format("Test exception from class: %s",
this.getClass().getSimpleName());
throw new RuntimeException(msg);
}
}
Creating class with @ControllerAdvice
@ControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException (Exception exception, Model model) {
model.addAttribute("exception", exception);
return "exception-page";
}
}
src/main/webapp/WEB-INF/views/exception-page.jsp
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<h3>Exception Page</h3>
<p>
status:<br/><%=response.getStatus()%>
</p>
<p>
Exception Message:<br/>${exception.message}
</p>
<p>
Exception type:<br/>${exception['class'].name}
</p>
</body>
</html>
JavaConfig class
@EnableWebMvc
@ComponentScan("com.logicbig.example")
public class AppConfig {
@Bean
public ViewResolver viewResolver () {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Running embedded tomcat
mvn tomcat7:run-war
Output
/test1
/test2
Example Project
Dependencies and Technologies Used: - spring-webmvc 4.3.5.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|