為什么要使用全局異常處理器:如果不加以異常處理,錯(cuò)誤信息肯定會(huì)拋在瀏覽器頁(yè)面上,這樣很不友好,所以必須進(jìn)行異常處理。
異常處理思路
系統(tǒng)的dao、service、controller出現(xiàn)都通過(guò)throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進(jìn)行異常處理,如下圖:
創(chuàng)建異常處理器:GlobalException:
/*
* Copyright (c) 2020, 2024, All rights reserved.
*
*/
package com.by.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <p>Project: SpringMVC - GlobleException</p>
* <p>Powered by scl On 2024-01-10 14:09:52</p>
* <p>描述:<p>
*
* @author 孫臣龍 [1846080280@qq.com]
* @version 1.0
* @since 17
*/
@Component
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
/**
* 1.發(fā)郵件、發(fā)信息
* 2.跳轉(zhuǎn)到錯(cuò)誤頁(yè)面
*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",e.getMessage());
modelAndView.setViewName("exception");
return modelAndView;
}
}
? 編寫controller:ExceptionController:
/*
* Copyright (c) 2020, 2024, All rights reserved.
*
*/
package com.by.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* <p>Project: SpringMVC - execptionController</p>
* <p>Powered by scl On 2024-01-10 14:14:44</p>
* <p>描述:<p>
*
* @author 孫臣龍 [1846080280@qq.com]
* @version 1.0
* @since 17
*/
@Controller
@RequestMapping("/account")
public class ExceptionController {
@RequestMapping("/findException")
public String findException() throws Exception{
System.out.println(4/0);
return "exception";
}
}
在index.jsp里面定義超鏈接:?
<a href="/account/findException">全局異常處理器</a>
結(jié)果展示:
?項(xiàng)目結(jié)構(gòu):
?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-791506.html
項(xiàng)目配置可參考:Spring MVC文件上傳?。?!-CSDN博客文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-791506.html
到了這里,關(guān)于Spring MVC配置全局異常處理器?。?!的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!