SpringMVC九:异常处理器

异常处理器

一、概述
  1. spingMVC中的异常处理器

    在这里插入图片描述

二、基于配置的异常处理
  1. 在springMVC中配置
    <!-- 8.配置异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 
                    properties的键:表示处理器方法执行过程中出现的异常
                    properties的值:表示若出现指定异常时,设置一个新的视图名称,跳转到指定的页面
                -->
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
        <!-- 
    		 该属性可以设置一个键(此处这个键就是"ex"),用来存储我们的异常信息,
    		 该信息默认被存储在请求作用域中 
    	-->
        <property name="exceptionAttribute" value="ex"></property>
    </bean>
    
  2. html
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>title</title>
    </head>
    <body>
        <h1>出现错误</h1>
        <!-- 共享到请求作用域中的数据 -->
    	<p th:text="${ex}"></p>
    </body>
    </html>
    
  3. controller
    @Controller
    public class ExceptionController {
        @RequestMapping("/exceptionHandlerTest")
        public String exceptionHandlerTest() {
            // 如果出现异常,就会自动跳转到对应的错误页面
            System.out.println(1/0);
            return "success";
        }
    }
    
  4. 相应页面

    在这里插入图片描述

三、基于注解的异常处理
  1. 使用到的两个注解
    @ControllerAdvice
    @ExceptionHandler(value = { })
  2. 创建异常处理的配置类
    @ControllerAdvice
    public class HandlerExceptionController {
        // 如果出现该注解中的任意一个错误类,就会执行该方法作为控制器方法
        @ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
        public String handlerExceptionTest(Exception ex, Model model) {
            model.addAttribute("ex", ex);
            return "error";
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

e_nanxu

感恩每一份鼓励-相逢何必曾相识

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值