關(guān)于SpringMVC的異常處理機(jī)制詳細(xì)解讀
SpringMVC異常處理機(jī)制
(一)項(xiàng)目前準(zhǔn)備
- 首先參照文章Spring課程工程構(gòu)建+SpringMVC簡介及其快速入門搭建項(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類和視圖頁面
- ④使用注解配置Controller類中業(yè)務(wù)方法的映射地址
- ⑤配置SpringMVC核心文件spring-mvc.xml。
- 項(xiàng)目基本框架

- 在DemoService里面創(chuàng)建多個(gè)方法,用于測試異常的類型。
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("拋出類型轉(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類里面進(jìn)行調(diào)用測試方法,用于異常的展示。
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)限開放以及組件掃描。
<?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)限開放-->
<mvc:default-servlet-handler/>
<!--4、組件掃描 掃描Controller-->
<context:component-scan base-package="com.itheima.controller"/>
</beans>- 在web.xml文件進(jìn)行基本的配置,例如監(jiān)聽器、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)聽器-->
<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ò)誤提示頁面</h1>
</body>
</html>(二)項(xiàng)目異常測試
2.1 異常處理的思路
- 系統(tǒng)中異常包括兩類:預(yù)期異常和運(yùn)行時(shí)異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規(guī)范代碼開發(fā)、測試等手段減少運(yùn)行時(shí)異常的發(fā)生。
- 系統(tǒng)的Dao、Service、Controller出現(xiàn)都通過throws Exception向上拋出,最后由SpringMVC前端控制器交由異常處理器進(jìn)行異常處理,如下圖:

2.2 異常處理兩種方式
①、使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolverr
②、實(shí)現(xiàn)Spring的異常處理接口HandlerExceptionResolver 自定義自己的異常處理器
2.3 簡單異常處理器 SimpleMappingExceptionResolver
- SpringMVC已經(jīng)定義好了該類型轉(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)行訪問,頁面會(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>- 再次訪問
localhost:8080/show,頁面就不再會(huì)出現(xiàn)上次的異常頁面。而是顯示我們?cè)O(shè)置的error.jsp頁面。

(2)根據(jù)錯(cuò)誤異常類型,進(jìn)行自定義設(shè)定的錯(cuò)誤視圖跳轉(zhuǎn)
- 類型轉(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>
- 自定義類型異常
<!--配置異常處理器-->
<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異常處理器類
①、創(chuàng)建異常處理器類實(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","類轉(zhuǎn)換異常");
}
modelAndView.setViewName("error");
return modelAndView;
}
}②、在spring-mvc.xml里面配置異常處理器
<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>
③、在error.jsp中,編寫異常頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>通用的錯(cuò)誤提示頁面</h1>
<h1>${info}</h1>
</body>
</html>④測試異常跳轉(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("拋出類型轉(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)文章
Mockito 結(jié)合 Springboot 進(jìn)行應(yīng)用測試的方法詳解
這篇文章主要介紹了Mockito 結(jié)合 Springboot 進(jìn)行應(yīng)用測試的方法詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
分布式服務(wù)Dubbo+Zookeeper安全認(rèn)證實(shí)例
下面小編就為大家分享一篇分布式服務(wù)Dubbo+Zookeeper安全認(rèn)證實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
Nacos-SpringBoot框架啟動(dòng)不加載bootstrap.yml的解決
這篇文章主要介紹了Nacos-SpringBoot框架啟動(dòng)不加載bootstrap.yml的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
關(guān)于maven使用過程中無法導(dǎo)入依賴的一些總結(jié)
這篇文章主要介紹了關(guān)于maven使用過程中無法導(dǎo)入依賴的一些總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

