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>

測試正常

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