SpringMVC —— 11、异常处理器

目录

1、基于配置的异常处理

 2、基于注解的异常处理


1、基于配置的异常处理

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver

HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver 和 SimpleMappingExceptionResolver,如下图

① 在 TestController 中添加方法,在其中创建一个异常(1 / 0)

    @RequestMapping("/testExceptionHandle")
    public String testExceptionHandle(){
        System.out.println(1 / 0);
        return "success";
    }

② 在 src/main/webapp/WEB-INF/templates 下新建 error.html 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>错误页面</title>
</head>
<body>
    出现错误
    <!-- 设置了property name="exceptionAttribute"后就可以获取放在请求域中的异常信息了 -->
    <p th:text="${ex}"></p>
</body>
</html>

③ 在 springMVC.xml 中配置异常处理

    <!-- 配置异常处理 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <!-- 设置对应异常要跳转的页面 -->
            <props>
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
        <!-- 设置了这个后,就可以设置一个键存储异常信息(默认存储到请求域中),value是键,异常信息是值 -->
        <property name="exceptionAttribute" value="ex"></property>
    </bean>

④ 在 index.html 中添加测试链接

    <!-- 测试异常处理 -->
    <a th:href="@{/testExceptionHandle}">测试异常处理</a>

⑤ 运行测试,页面会跳转到 错误页面,并且显示异常信息

 2、基于注解的异常处理

① 创建一个控制器类

@ControllerAdvice
public class ExceptionController {

    // 当出现value中的任一异常时,会通过该方法来作为新的控制器方法来执行
    @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
    public String testException(Exception ex, Model model){
        // 将异常信息传到请求域
        model.addAttribute("ex", ex);
        return "error";
    }

}

② 将上面 springMVC.xml 中配置的异常处理注释掉,然后运行测试,跳转成功并显示了异常信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值