spring MVC异常捕获机制
spring MVC 提供了异常捕获机制
org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
可以针对不同的异常,进入不同的视图,配置如下:
<!--定义异常处理页面-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.transaction.CannotCreateTransactionException">dbNotConnected</prop>
<prop key="org.hibernate.exception.JDBCConnectionException">dbNotConnected</prop>
<prop key="java.sql.SQLException">dbNotConnected</prop>
<prop key="java.net.ConnectException">dbNotConnected</prop>
</props>
</property>
</bean>
如上,只要是连接数据库失败的异常,均显示视图:dbNotConnected
SimpleMappingExceptionResolver核心逻辑
为什么视图名没有jsp后缀
因此此时的视图路径的处理逻辑与常规的控制器相同,即:
使用注解
你也可以使用有注解@ExceptionHandler 的方法.
当在一个控制器里面声明的时候,该方法将会应用于该控制器(及其子类)中被@RequestMapping注解的方法抛出的异常.
当然,你也可以在@ControllerAdvice注解的class中,那么该方法将对所有控制器中@RequestMapping 方法抛出的异常.
spring mvc 官网文档:
You can do that with @ExceptionHandler methods. When declared within a controller such methods apply to exceptions raised by @RequestMapping methods of that contoroller (or any of its sub-classes). You can also declare an @ExceptionHandler method within an @ControllerAdvice class in which case it handles exceptions from @RequestMapping methods from any controller. The @ControllerAdvice annotation is a component annotation, which can be used with classpath scanning. It is automatically enabled when using the MVC namespace and the MVC Java config, or otherwise depending on whether the ExceptionHandlerExceptionResolver is configured or not. Below is an example of a controller-local @ExceptionHandler method:
@Controller
public class SimpleController {
// @RequestMapping methods omitted ...
@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOException(IOException ex) {
// prepare responseEntity
return responseEntity;
}
}