如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
?
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;
/**
* 将全局错误放到容器
*/
@Component
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
/**
* 1.发短信、发邮箱
* 2.设置全局的错误页面
* 3.把异常信息传递到异常页面
*/
ModelAndView mv = new ModelAndView();
mv.addObject("msg",e.getMessage());
mv.setViewName("exception");
return mv;
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount">异常处理器</a>
controller层书写错误
@RequestMapping("/findAccount")
public String findAccount(Model model){
model.addAttribute("msg","欢迎你,Spring MVC");
int a=1/0;
return "success";
}
编写exception.jsp页面
<%--
Created by IntelliJ IDEA.
User: A
Date: 2024/1/10
Time: 14:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
程序出错了:${msg}<br>
嘎了、嘎了、嘎了.....,请联系管理员:111111
</body>
</html>