SpringMVC異常處理

Kevinnsm發表於2020-11-26

異常處理的兩種方式

#.使用SpringMVC提供的異常處理器SimpleMappingExceptionResolver
#.使用Spring的異常處理介面HandlerExceptionResolver自定義自己的異常處理機制


我們先看一下不使用異常處理器的情況
1.在service層模擬異常情況(介面程式碼省略)

public class DemoServiceImpl implements DemoService {
    public void show1() {
        System.out.println("丟擲型別轉換異常....");
        Object str = "zhangsan";
        Integer num = (Integer)str;
    }

    public void show2() {
        System.out.println("丟擲除零異常....");
        int i = 1/0;
    }

    public void show3() throws FileNotFoundException {
        System.out.println("檔案找不到異常....");
        InputStream in = new FileInputStream("C:/xxx/xxx/xxx.txt");
    }

    public void show4() {
        System.out.println("空指標異常.....");
        String str = null;
        str.length();
    }

    public void show5() throws MyException {
        System.out.println("自定義異常....");
        throw new MyException();
    }
}

2.編寫Controller層

@Controller
public class DemoController {

    @Autowired
    private DemoService demoService;

    @RequestMapping(value = "/show")
    public String show() throws FileNotFoundException, MyException {
        System.out.println("show running......");
        //demoService.show1();
        //demoService.show2();
        //demoService.show3();
        //demoService.show4();
        demoService.show5();
        return "index";
    }

}

3.配置applicaitonContext.xml檔案

<?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"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--將service注入到spring容器-->
    <bean id="demoService" class="com.hao.service.DemoServiceImpl"></bean>


</beans>

4.配置spring-mvc.xml檔案

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

    <!--1、mvc註解驅動-->
    <mvc:annotation-driven/>

    <!--2、配置檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--3、靜態資源許可權開放-->
    <mvc:default-servlet-handler/>

    <!--4、元件掃描  掃描Controller-->
    <context:component-scan base-package="com.hao.controller"/>

</beans>

5.啟動tomcat訪問
在這裡插入圖片描述
我們不可能讓使用者訪問時看到這種頁面一般的做法就是當某個程式出現異常時,讓它跳轉到某個jsp頁面

使用SpringMVC提供的異常處理器SimpleMappingExceptionResolver

6.所以我們可以在spring-mvc.xml中加入這一段程式碼
defaultEroorView:當後面map集合裡面的異常都不匹配時,才會執行這個預設的配置
value:代表檢視,不寫error.jsp是因為我在上文中已經配置了檢視解析器

 <!--配置異常處理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"/>
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="error1"/>
                <entry key="com.hao.exception.MyException" value="error2"/>
            </map>
        </property>
    </bean>

7.再次啟動tomcat進行訪問(出現異常就會幫我們跳轉到錯誤頁面)
在這裡插入圖片描述





自定義異常處理器

編寫異常處理類

public class MyExceptionResolver implements HandlerExceptionResolver {

    /*
        引數Exception:異常物件
        返回值ModelAndView:跳轉到錯誤檢視資訊
     */
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();

        if(e instanceof MyException){
            modelAndView.addObject("info","自定義異常");
        }else if(e instanceof ClassCastException){
            modelAndView.addObject("info","類轉換異常");
        }

        modelAndView.setViewName("error");

        return modelAndView;
    }
}

2.將自定義異常處理類配置到spring-mvc.xml檔案中

 <bean class="com.hao.resolver.MyExceptionResolver"/>

相關文章