Springboot整合(5)——全局异常处理
Springboot整合(5)——全局异常处理
1. 编写BaseController,在BaseController中使用@ExceptionHandler做异常的逻辑处理
publicclass BaseController {
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 运行时异常
*/
@ExceptionHandler({ RuntimeException.class })
@ResponseBody
public ReturnResult otherException(RuntimeException exception) {
exception.printStackTrace();
returnnew ReturnResult(0, "服务器内部错误!");
}
}
2. 编写UserController继承BaseController (注意把之前写在indexController里用于测试的@RequestMapping(value = "user/list")删除)
@Controller
publicclass UserController extends BaseController {
privatestaticfinal Log LOG = LogFactory.getLog(UserController.class);
@Resource
private UserService userService;
@RequestMapping(value = "user/add", method = { RequestMethod.GET, RequestMethod.POST })
public String add() {
return"user/add";
}
@RequestMapping(value = "api/user/add", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public ReturnResult add(SysUser user) {
returnuserService.add(user);
}
@RequestMapping(value = "user/list", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView list() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("result", userService.list());
return new ModelAndView("user/list", model);
}
}
3. list.jsp和add.jsp
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>user list</title>
</head>
<body>
<table border=1>
<tr>
<th>UserName</th>
<th>Mobilephone</th>
<th>LoginName</th>
</tr>
<c:forEach items="${result.data.list}" var="user">
<tr>
<td align="center">${user.userName }</td>
<td align="center">${user.mobilephone }</td>
<td align="center">${user.loginName }</td>
</tr>
</c:forEach>
</table>
<a href="<%=basePath%>/user/add">Add</a>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<%=basePath%>vendors/jquery/jquery.min.js"></script>
<title>add user</title>
<script type="text/javascript">
function add() {
var url = "<%=basePath%>/api/user/add";
var datas = {
userName : $("#userName").val(),
loginName : $("#loginName").val(),
loginPassword : $("#loginPassword").val(),
mobilephone : $("#mobilephone").val(),
};
$.ajax({
type : 'POST',
cache : false,
url : url,
data : datas,
async : false,
success : function(result) {
$("#message").html(result.message);
if (result.code == 1) {
window.location = "<%=basePath%>user/list";
}
},
error : function(result) {
alert(result);
}
});
}
</script>
</head>
<body>
<form id="loginForm" action="<%=basePath%>api/user/add" method="post">
userName : <input type="text" id="userName" name="userName"><br>
loginName : <input type="text" id="loginName" name="loginUsername"><br>
loginPassword : <input type="text" id="loginPassword" name="loginPassword"><br>
mobilephone : <input type="text" id="mobilephone" name="mobilephone"><br>
<a href="javascript:add();">Submit</a> <a href="<%=basePath%>/user/list">Return</a>
</form>
<p id="message"></p>
</body>
</html>
4. 测试,正常情况下,运行正常。
5. 非正常情况下,如在service中添加异常代码,该异常会被全局异常捕获,前台提示服务器异常
补充:本节写的有点凌乱,这里理一下整体思路:
① BaseController作为所有Controller的基类,使用ExceptionHandler注解对所有的异常做统一处理,包括mapper(dao层),serviec层,controller层的异常。
② 当前因为还没有整合数据校验和shiro,所以BaseController中只处理了运行时异常。之后随着进一步整合会加入其他异常处理,当然,还可以根据自己项目做自定义异常的处理
③ 所有异常都使用了ResponseBody注解,仅返回数据不返回视图。本文的整体设计为前台统一使用ajax访问后台逻辑。如果全部用视图方式返回,就不需要用ResponseBody注解,可以根据项目自行调整。
④ 返回结果全部用ReturnResult封装,便于前端做统一处理。本文主旨在于探讨后端的设计思路,固前端不会给出详细代码设计,可以给一个简单的设计思路:编写一个公用jsp,写入一个隐藏域(model dialog),在每次请求后端返回数据后,用这个model dialog显示提示信息。