欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于SpringMVC的異常處理機(jī)制詳細(xì)解讀

 更新時(shí)間:2023年05月16日 09:56:36   作者:bfhonor  
這篇文章主要介紹了關(guān)于SpringMVC的異常處理機(jī)制詳細(xì)解讀,SpringMVC是目前主流的Web?MVC框架之一,本文將分析SpringMVC的異常處理內(nèi)容,需要的朋友可以參考下

SpringMVC異常處理機(jī)制

(一)項(xiàng)目前準(zhǔn)備

  • 首先參照文章Spring課程工程構(gòu)建+SpringMVC簡(jiǎn)介及其快速入門(mén)搭建項(xiàng)目搭建好一個(gè)項(xiàng)目itheima_spring_exception
  • 在創(chuàng)建好的項(xiàng)目里面根據(jù)上面的文章,依次
    • ①導(dǎo)入SpringMVC相關(guān)坐標(biāo)
    • ②配置SpringMVC核心控制器DispathcerServlet
    • ③創(chuàng)建Controller類(lèi)和視圖頁(yè)面
    • ④使用注解配置Controller類(lèi)中業(yè)務(wù)方法的映射地址
    • ⑤配置SpringMVC核心文件spring-mvc.xml。
  • 項(xiàng)目基本框架

在這里插入圖片描述

  • 在DemoService里面創(chuàng)建多個(gè)方法,用于測(cè)試異常的類(lèi)型。
package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileNotFoundException;
public interface DemoService {
    void show1();
    void show2();
    void show3() throws FileNotFoundException;
    void show4();
    void show5() throws MyException;
}
  • DemoServiceImpl實(shí)現(xiàn)接口DemoService里面的方法。
package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DemoServiceImpl implements DemoService{
    public void show1(){
        System.out.println("拋出類(lèi)型轉(zhuǎn)換異常...");
        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("文件找不到異常...");
        FileInputStream in = new FileInputStream("D:/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();
    }
}
  • 在DemoController類(lèi)里面進(jìn)行調(diào)用測(cè)試方法,用于異常的展示。
package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;
    @RequestMapping(value="/show")
    public String show(@RequestParam(value="name",required=true) String name) throws FileNotFoundException, MyException {
        System.out.println("show running......");
        demoService.show1();
        //demoService.show2();
        //demoService.show3();
        //demoService.show4();
        //demoService.show5();
        return "index";
    }
}
  • 在MyException自定義一個(gè)異常。
package com.itheima.exception;
public class MyException extends Exception{}
  • 在applicationContex.xml配置DemoServiceImpl的bean標(biāo)簽。
<?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
">
    <bean id="demoService" class="com.itheima.service.DemoServiceImpl"></bean>
</beans>
  • 在spring-mvc.xml文件里面進(jìn)行基本的配置,例如mvc注解驅(qū)動(dòng)、視圖管理器、靜態(tài)資源權(quán)限開(kāi)放以及組件掃描。
<?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注解驅(qū)動(dòng)-->
    <mvc:annotation-driven/>
    <!--2、配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--3、靜態(tài)資源權(quán)限開(kāi)放-->
    <mvc:default-servlet-handler/>
    <!--4、組件掃描  掃描Controller-->
    <context:component-scan base-package="com.itheima.controller"/>
</beans>
  • 在web.xml文件進(jìn)行基本的配置,例如監(jiān)聽(tīng)器、SpringMVC的前端控制器以及映射地址。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
	<!--配置監(jiān)聽(tīng)器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
	<!--配置SpringMVC的前端控制器-->
	<servlet>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <!--加載Spring-mvc.xml文件,在配置控制器的時(shí)候告知配置文件-->
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>classpath:spring-mvc.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<!--配置映射地址-->
	<servlet-mapping>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

index.jsp文件

<html>
	<body>
		<h2>Hello World!</h2>
	</body>
</html>

error.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用的錯(cuò)誤提示頁(yè)面</h1>
</body>
</html>

(二)項(xiàng)目異常測(cè)試

2.1 異常處理的思路

  • 系統(tǒng)中異常包括兩類(lèi):預(yù)期異常和運(yùn)行時(shí)異常RuntimeException,前者通過(guò)捕獲異常從而獲取異常信息,后者主要通過(guò)規(guī)范代碼開(kāi)發(fā)、測(cè)試等手段減少運(yùn)行時(shí)異常的發(fā)生。
  • 系統(tǒng)的Dao、Service、Controller出現(xiàn)都通過(guò)throws Exception向上拋出,最后由SpringMVC前端控制器交由異常處理器進(jìn)行異常處理,如下圖:

在這里插入圖片描述

2.2 異常處理兩種方式

①、使用Spring MVC提供的簡(jiǎn)單異常處理器SimpleMappingExceptionResolverr

②、實(shí)現(xiàn)Spring的異常處理接口HandlerExceptionResolver 自定義自己的異常處理器

2.3 簡(jiǎn)單異常處理器 SimpleMappingExceptionResolver

  • SpringMVC已經(jīng)定義好了該類(lèi)型轉(zhuǎn)換器,在使用時(shí)可以根據(jù)項(xiàng)目情況進(jìn)行相應(yīng)異常與視圖的映射配置

在這里插入圖片描述

(1)默認(rèn)錯(cuò)誤視圖

  • 當(dāng)我們啟動(dòng)服務(wù)器時(shí)候,對(duì)localhost:8080/show進(jìn)行訪問(wèn),頁(yè)面會(huì)出現(xiàn)異常

在這里插入圖片描述

  • 當(dāng)我們?cè)?code>spring-mvc.xml文件中進(jìn)行異常的配置
<!--配置異常處理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!--默認(rèn)錯(cuò)誤視圖-->
    <property name="defaultErrorView" value="error"/>
</bean>
  • 再次訪問(wèn)localhost:8080/show,頁(yè)面就不再會(huì)出現(xiàn)上次的異常頁(yè)面。而是顯示我們?cè)O(shè)置的error.jsp頁(yè)面。

在這里插入圖片描述

(2)根據(jù)錯(cuò)誤異常類(lèi)型,進(jìn)行自定義設(shè)定的錯(cuò)誤視圖跳轉(zhuǎn)

  • 類(lèi)型轉(zhuǎn)換異常
<!--配置異常處理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <map>
            <entry key="java.lang.ClassCastException" value="error1"></entry>
        </map>
    </property>
</bean>

在這里插入圖片描述

  • 自定義類(lèi)型異常
<!--配置異常處理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <map>
            <entry key="com.itheima.exception.MyException" value="error2"></entry>
        </map>
    </property>
</bean>

在這里插入圖片描述

2.4 自定義異常處理步驟

  • src\main\java里面創(chuàng)建com.itheima.resolver包,然后創(chuàng)建MyExceptionResolver異常處理器類(lèi)

①、創(chuàng)建異常處理器類(lèi)實(shí)現(xiàn)HandlerExceptionResolver

package com.itheima.resolver;
import com.itheima.exception.MyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyExceptionResolver implements HandlerExceptionResolver {
    /*參數(shù)Exception 異常對(duì)象
    * 返回值ModelAndView 跳轉(zhuǎn)到視圖信息*/
    @Override
    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","類(lèi)轉(zhuǎn)換異常");
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

②、在spring-mvc.xml里面配置異常處理器

<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>

③、在error.jsp中,編寫(xiě)異常頁(yè)面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用的錯(cuò)誤提示頁(yè)面</h1>
    <h1>${info}</h1>
</body>
</html>

④測(cè)試異常跳轉(zhuǎn)

package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;
    @RequestMapping(value="/show")
    public String show() throws FileNotFoundException, MyException {
        System.out.println("拋出類(lèi)型轉(zhuǎn)換異常...");
        Object str = "zhangsan";
        Integer num = (Integer) str;
        return "index";
    }
}

在這里插入圖片描述

到此這篇關(guān)于關(guān)于SpringMVC的異常處理機(jī)制詳細(xì)解讀的文章就介紹到這了,更多相關(guān)SpringMVC的異常處理機(jī)制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論