SpringMVC
1. 异常处理
1.1 异常处理思路
系统中异常包括两类: 预期异常和运行时异常 RuntimeException
,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的 dao
、 service
、 controller
出现都通过 throws Exception
向上抛出,最后由 springmvc
前端控制器DispatcherServlet
交由异常处理器进行异常处理,如下图:
1.2 SpringMVC的异常处理
1. 自定义异常类和错误页面
package com.spg.exception;
/**
* 自定义异常
*/
public class SysException extends Exception {
// 存储提示信息
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>error</title>
</head>
<body>
${errorMsg}
</body>
</html>
2. 自定义异常处理器
package com.spg.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理器
*/
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常业务逻辑
* @param request
* @param response
* @param handler
* @param ex
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 获取到异常对象
SysException e = null;
if(ex instanceof SysException){
e = (SysException) ex;
} else {
e = new SysException("系统正在维护...");
}
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", e.getMessage());
mv.setViewName("error");
return mv;
}
}
3. 配置异常处理器
<!-- 配置异常处理器 -->
<bean id="sysExceptionResolver" class="com.spg.exception.SysExceptionResolver"/>
4. JSP页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>执行成功!</h3>
</body>
</html>
package com.spg.controller;
import com.spg.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了...");
try {
// 模拟异常
int a = 10/0;
} catch (Exception e) {
// 打印异常信息
e.printStackTrace();
// 抛出自定义异常
throw new SysException("查询所有用户出现错误了...");
}
return "success";
}
}