全局异常处理

异常的结构:

        Throwable: 异常的根类。

                Error: 错误。这个错误程序员无法解决。

                Exception:异常。

                        编译异常:

                        运行时异常: RuntimeException: 只会在运行的时候出现。

(1)自定义一个全局异常处理类

@ControllerAdvice //该类为异常处理类。  Advice建议
public class MyHandler {

    //ExceptionHandler异常发生时执行的方法。
    @ExceptionHandler(value = ArithmeticException.class) //如果不使用value默认处理Throwable异常。
    public String handlerException(){
        System.out.println("!~~~~~~~~~~~~~~~~~~");
        return "error";
    }

}

2.一定要让springmvc扫描到该异常处理类。

<context:component-scan base-package="com.controller,com.handler"/>

com.handler就是异常类所在的包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--1.包扫描 扫描我们自己的控制层类所在的包或者父包-->
    <context:component-scan base-package="com.controller,com.handler"/>
    <!--拦截器-->
    <mvc:annotation-driven/>
    <!--释放静态资源-->
    <mvc:default-servlet-handler/>

    <!--视图解析器 前补/ 后补 .jsp-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

当出现ArithmeticException异常时,会跳转到/error.jsp页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值