spring MVC异常捕获机制

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;
  }

}
阅读更多
文章标签: spring mvc
个人分类: spring-mvc
上一篇freemark 条件判断
下一篇javascript 原型链和继承(1)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭