为什么要使用全局异常处理器:如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
异常处理思路
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
创建异常处理器: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 {@Overridepublic ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {/*** 1.发邮件、发信息* 2.跳转到错误页面*/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>
结果展示:
项目结构:
项目配置可参考:Spring MVC文件上传!!!-CSDN博客