1.将SimpleMappingExceptionResolver注入进ioc容器中
<!-- 统一异常处理 -->
<beans:bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 设置页面 -->
<beans:property name="defaultErrorView" value="error"/>
</beans:bean>
2.编写一个会报错的controller控制器方法:
@RequestMapping("/testex")
public String testex(){
//程序报错
System.out.println(1/0);
return "upload";
}
3.当访问该控制器时,程序自动跳到自定义的error.jsp页面,页面与后台均未报错。
1.使用注解@ExceptionHandler,编写一个方法,放在控制器里即可
@ExceptionHandler
public String handerException(HttpServletRequest req,Exception ex){
req.setAttribute("ex", ex);
return "error";
}
后两步骤与第一种方式相同。
通过实现HandlerExceptionResolver接口来实现自定义异常处理,这里也可以根据Exception类型的不同来跳转不同的error页面。
@Component
public class JymMVCException implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) {
String xhr = request.getHeader("X-Requested-With");
//判断是否为ajax请求出现的异常,如果是ajax异常,传mapper对象到前台回调函数中
if(xhr!=null&&"XMLHttpRequest".equals(xhr)){
try {
PrintWriter out = response.getWriter();
Map<String, Object> mapper = new HashMap<String, Object>();
mapper.put("success", false);
mapper.put("msg", "error");
ObjectMapper om = new ObjectMapper();
om.writeValue(out, mapper);
out.write("请求异常");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//非ajax异常处理
ModelAndView mv = new ModelAndView();
mv.addObject("ex", exception);
mv.setViewName("error");
return mv;
}
}
前台页面
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>index</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
})
function tojson(){
var data = {"name":"jym","age":"18"};
$.ajax({
url:"${pageContext.request.contextPath}/model/tobean",
type: "post",
data: data,
success:function(data){
console.log(data)
}
})
}
</script>
</head>
<body class="bg_block">
<input type="button" name="btn" value="转换bean" id="btn_json" onclick="tojson();"/>
</body>
</html>
controller控制器:
@RequestMapping(value= "/tobean", method = RequestMethod.POST)
@ResponseBody
public void jsonToBean(Student student){
System.out.println(1/0);
}
前台页面控制台成功打印出错误信息