正常的浏览器显示异常
前端控制器接收到异常,如果没有部署异常处理器,会直接在浏览器抛出不友好的异常提示信息。
Controller代码
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("testException")
public String testException() throws Exception{
System.out.println("testException执行了。。。");
//模拟异常
int a=10/0;
return "success";
}
}
jsp页面设置跳转
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>异常处理</h2>
<a href="user/testException">异常处理</a>
</body>
</html>
处理结果
SpringMVC异常处理
前端控制器接收到浏览器信息,会调用异常处理器组件,通过异常处理器处理异常,返回给浏览器有好的错误提示页面。
具体步骤:
- 编写自定义异常类(做提示信息的)
- 编写异常处理器
- 配置异常处理器(跳转到提示页面)
配置前端异常处理器(SpringMVC.xml)
<!-- 配置异常处理器-->
<bean id="sysExceptionResolver"
class="cn.itcast.exception.SysExceptionResolver"></bean>
exception代码
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;
}
}
controller代码
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("testException")
public String testException() throws Exception{
System.out.println("testException执行了。。。");
try {
//模拟异常
int a=10/0;
} catch (Exception e) {
//打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("查询所有用户出现错误了。。。");
}
return "success";
}
}
SysException.java类
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;
}
}
error.jsp页面获取错误信息
<body>
${errorMsg}
</body>
处理结果