SpringMVC中的攔截器與異常處理機(jī)制詳解
一、SpringMVC攔截器
1.1 攔截器(interceptor)的作用
SpringMVC的攔截器類似于Servlet開發(fā)中的過濾器Filter,用于對(duì)處理器進(jìn)行預(yù)處理和后處理
將攔截器按一定的順序聯(lián)結(jié)成一條鏈,這條鏈被稱為攔截器鏈(Interceptor Chain)。在訪問被攔截的方法或字段時(shí),攔截器鏈中的攔截器就會(huì)按其之前定義的順序被調(diào)用。攔截器也是AOP思想的具體實(shí)現(xiàn)。
1.2 攔截器和過濾器區(qū)別
| 區(qū)別 | 過濾器(Filter) | 攔截器(Interceptor) |
| 使用范圍 | 是 servlet 規(guī)范中的一部分,任何 Java Web 工程都可以使用 | 是 SpringMVC 框架自己的,只有使用了 SpringMVC 框架的工程才能用 |
| 攔截范圍 | 在 url-pattern 中配置了/*之后, 可以對(duì)所有要訪問的資源攔截 | 在<mvc:mapping path= "" />中配置了/**之后,也可以多所有資源進(jìn)行攔截,但是可以通過<mvc:exclude-mapping path= "" />標(biāo)簽排除不需要攔截的資源 |
1.3 攔截器快速入門
自定義攔截器三個(gè)步驟
①創(chuàng)建攔截器類實(shí)現(xiàn)HandlerInterceptor接口
②配置攔截器
③測試攔截器的攔截效果
代碼實(shí)現(xiàn)
① 創(chuàng)建攔截器類實(shí)現(xiàn)HandlerInterceptor接口
public class MyInterceptor1 implements HandlerInterceptor {
@Override
//在目標(biāo)方法執(zhí)行之前 執(zhí)行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
String param = request.getParameter("param");
if ("yes".equals(param)){
return true;
}else {
request.getRequestDispatcher("/error.jsp").forward(request,response);
return false;
}
//return true; //返回true表示放行,返回false表示不放行
}
@Override
//在目標(biāo)方法執(zhí)行之后,視圖對(duì)象返回之前 執(zhí)行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
modelAndView.addObject("name","我被改了~");
System.out.println("postHandle...");
}
@Override
//在流程都執(zhí)行完畢后 執(zhí)行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
② 配置攔截器
<!--配置攔截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--對(duì)哪些資源執(zhí)行攔截操作-->
<mvc:mapping path="/**"/>
<bean class="com.learn.interceptor.MyInterceptor1"/>
</mvc:interceptor>
</mvc:interceptors>③ 測試攔截器的攔截效果(編寫目標(biāo)方法)
@Controller
public class TargetController {
@RequestMapping("/target")
public ModelAndView show(){
System.out.println("目標(biāo)資源執(zhí)行...");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name","gugumao");
modelAndView.setViewName("index");
return modelAndView;
}
}這里url不帶param參數(shù)或者param參數(shù)不為yes的話會(huì)跳轉(zhuǎn)到error.jsp頁面中


控制臺(tái)打印順序如下:

1.4 多攔截器操作
同上,再編寫一個(gè)MyHandlerInterceptor2操作,測試執(zhí)行順序如下:

1.5 攔截器方法說明
| 方法名 | 說明 |
| preHandle() | 方法將在請(qǐng)求處理之前進(jìn)行調(diào)用,該方法的返回值是布爾值Boolean類型的, 當(dāng)它返回為 false 時(shí),表示請(qǐng)求結(jié)束,后續(xù)的Interceptor 和Controller 都不會(huì)再執(zhí)行;當(dāng)返回值為true 時(shí)就會(huì)繼續(xù)調(diào)用下一個(gè)Interceptor 的 preHandle 方法 |
| postHandle() | 該方法是在當(dāng)前請(qǐng)求進(jìn)行處理之后被調(diào)用,前提是 preHandle 方法的返回值為 true 時(shí)才能被調(diào)用,且它會(huì)在DispatcherServlet 進(jìn)行視圖返回渲染之前被調(diào)用,所以我們可以在這個(gè)方法中對(duì)Controller 處理之后的ModelAndView 對(duì)象進(jìn)行操作 |
| afterCompletion() | 該方法將在整個(gè)請(qǐng)求結(jié)束之后,也就是在DispatcherServlet 渲染了對(duì)應(yīng)的視圖之后執(zhí)行,前提是 preHandle 方法的返回值為true時(shí)才能被調(diào)用 |
二、SpringMVC異常處理機(jī)制
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 異常處理的兩種方式
- 使用SpringMVC提供的簡單異常處理器 SimpleMappingExceptionResolver
- 實(shí)現(xiàn)Spring的異常處理接口 HandlerExceptionRosolver 自定義自己的異常處理器
2.2.1 簡單異常處理器 SimpleMappingExceptionResolver
SpringMVC已經(jīng)定義好了該類型轉(zhuǎn)換器,在使用時(shí)可以根據(jù)項(xiàng)目情況進(jìn)行相應(yīng)異常與視圖的映射配置
<!--配置簡單映射異常處理器-->
<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.learn.exception.MyException" value="error2"/>
</map>
</property>
</bean>
2.2.2 自定義異常處理步驟
①創(chuàng)建異常處理器實(shí)現(xiàn)HandlerExceptionResolver接口
②配置異常處理器
③編寫異常頁面
④測試異常跳轉(zhuǎn)
代碼實(shí)現(xiàn)
創(chuàng)建異常處理器類實(shí)現(xiàn)HandlerExceptionResolver
public class MyExceptionResolver implements HandlerExceptionResolver {
/*
參數(shù)Exception:異常對(duì)象
返回值ModelAndView:跳轉(zhuǎn)到錯(cuò)誤視圖信息
*/
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//處理異常的代碼實(shí)現(xiàn)
//創(chuàng)建ModelAndView對(duì)象
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;
}
}配置異常處理器
<!--自定義異常處理器-->
<bean class="com.learn.resolver.MyExceptionResolver"/>編寫異常頁面
<%@ 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)
@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";
}
}到此這篇關(guān)于SpringMVC中的攔截器與異常處理機(jī)制詳解的文章就介紹到這了,更多相關(guān)SpringMVC攔截器與異常處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用easyexcel導(dǎo)出的excel文件,使用poi讀取時(shí)異常處理方案
這篇文章主要介紹了使用easyexcel導(dǎo)出的excel文件,使用poi讀取時(shí)異常處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
如何使用MybatisPlus快速進(jìn)行增刪改查詳解
增刪改查在日常開發(fā)中是再正常不多的一個(gè)需求了,下面這篇文章主要給大家介紹了關(guān)于如何使用MybatisPlus快速進(jìn)行增刪改查的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
淺析Java中ConcurrentHashMap的存儲(chǔ)流程
ConcurrentHashMap技術(shù)在互聯(lián)網(wǎng)技術(shù)使用如此廣泛,幾乎所有的后端技術(shù)面試官都要在ConcurrentHashMap技術(shù)的使用和原理方面對(duì)小伙伴們進(jìn)行360°的刁難,本文詳細(xì)給大家介紹一下ConcurrentHashMap的存儲(chǔ)流程,需要的朋友可以參考下2023-05-05
java基于swing實(shí)現(xiàn)的五子棋游戲代碼
這篇文章主要介紹了java基于swing實(shí)現(xiàn)的五子棋游戲代碼,主要涉及圖形界面與數(shù)組的用法,有不錯(cuò)的參考借鑒價(jià)值,需要的朋友可以參考下2014-11-11
SpringBoot集成EasyExcel實(shí)現(xiàn)百萬級(jí)別的數(shù)據(jù)導(dǎo)入導(dǎo)出實(shí)踐指南
本文將基于開源項(xiàng)目 springboot-easyexcel-batch 進(jìn)行解析與擴(kuò)展,手把手教大家如何在 Spring Boot 2.2.1 中集成 Alibaba EasyExcel,輕松實(shí)現(xiàn)百萬級(jí)數(shù)據(jù)的導(dǎo)入與導(dǎo)出2025-08-08
Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼
這篇文章主要介紹了Springboot實(shí)現(xiàn)根據(jù)條件切換注入不同實(shí)現(xiàn)類的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

