SpringMVC中三种异常处理的配置方式

1.为当前Controller配置错误处理

在当前控制器中通过注解@ExceptionHandler配置,当该Controller出现异常时,跳转到指定的页面(my01err.jsp)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/my01")
public class MyController01 {

    @ExceptionHandler
    public String myExceptionHandler(Exception e){
        System.out.println("记录异常日志..."+e);
        return "my01err";
    }

    @RequestMapping("/test01.action")
    public void test01(){
        int i = 1/0;
    }
}

my01err.jsp中的代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>my01err.jsp</title>
</head>
<body>
    服务器出错了哦~~~亲~~~~~~~
</body>
</html>

测试结果

2. 注解方式配置全局的错误处理

编写类MyGlobalExcpetionHandler,在该类上标注@ControllerAdvice,处理方法上标注@ExceptionHandler

@ControllerAdvice
public class MyGlobalExcpetionHandler {
    @ExceptionHandler
    public String MyGExceptionHandler(Exception e){
        System.out.println("全局异常日志....."+e);
        return "mygerr";
    }
}

测试类

@Controller
@RequestMapping("/my02")
public class MyController02 {
    @RequestMapping("/test01.action")
    public void test01(){
        String str = null;
        str.toUpperCase();
    }
}

测试结果

3. 配置文件方式配置全局错误处理

在springmvc.xml中配置

空指针的配置跳转到nullerr.jsp    io的跳转到ioerr.jsp   也能配置所以异常统一跳转到gerr

<?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">
    <!--配置包扫描-->
    <context:component-scan base-package="cn.tedu.web"/>
    <!--配置注解方式mvc-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--全局错误处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">nullerr</prop>
                <prop key="java.io.IOException">ioerr</prop>
                <prop key="java.lang.Throwable">gerr</prop>
            </props>
        </property>
    </bean>
</beans>

测试正常

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章