1.在spring-mvc.xml中进行配置
<bean class="com.test.util.page.WebExceptionResolver" />
2.WebExceptionResolver的实现
package com.test.util.page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class WebExceptionResolver
implements HandlerExceptionResolver
{
public static final Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class);
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
{
try {
if (!(request.getHeader("accept").contains("application/json") ||
(request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {//不是ajax请求
return new ModelAndView("/exception", "exception", e);
} else {
try {
response.setHeader("REQUEST_ERROR_KEY", "true");
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(new ResponseState(e).toString());
response.getWriter().flush();
response.getWriter().close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}finally{
logger.error("系统发生异常,访问路径:" + request.getServletPath());
}
}
}
3.ajax返回实体定义
package com.test.util.page;
import org.apache.ibatis.exceptions.TooManyResultsException;
import java.sql.SQLException;
/**
* 增删改时返回前端的判断实体
* @author Lihhz 2017-03-15
*
*/
public class ResponseState {
/**错误信息*/
protected String message;
/**错误编码*/
protected short code;
/**是否成功*/
protected boolean success;
/**返回数据*/
protected Object data;
public ResponseState() {
this.code = 0;
this.success = true;
this.data = null;
}
public ResponseState(String message) {
this.message = message;
}
public ResponseState(short code, String message) {
this.code = code;
this.message = message;
}
public ResponseState(boolean success, String message) {
this.success = success;
this.message = message;
}
public ResponseState(short code, boolean success, String message) {
this.code = code;
this.success = success;
this.message = message;
}
public ResponseState(Exception ex) {
this.code = -1;
this.success = false;
if (ex.getMessage() == null) {
this.message = "参数不正确或不完整";
} else if (ex.getCause() instanceof SQLException)
this.message = "服务器异常:执行数据库语句错误";
else if(ex.getCause() instanceof TooManyResultsException)
this.message = "应该查询出一条结果,但查询出多条结果.";
else
setMessage(ex.getMessage());
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
if (message != null)
message = message.replace("\"", "'").replace('\r', '\0');
this.message = message;
}
public short getCode() {
return this.code;
}
public void setCode(short code) {
this.code = code;
}
public boolean getSuccess() {
return this.success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
public String toString() {
StringBuffer sbJson = new StringBuffer("{\"code\":");
sbJson.append(this.code).append(",\"message\":\"").append(this.message)
.append("\",").append("\"success\":").append(this.success)
.append("}");
return sbJson.toString();
}
}
4.对于throw Exception的处理:exception.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
Exception e = (Exception)request.getAttribute("exception");
%>
<div id='exception-div-11111'></div>
<script type="text/javascript">
alert("服务器发生异常:异常信息:<%=e.getMessage()%>");
//如果是modal的话,关闭,解决页面不能点击的问题
if($('#exception-div-11111').parent().hasClass('modal-content')){
$('#exception-div-11111').parent().parent().parent().modal('hide');
$('#exception-div-11111').parent().parent().parent().removeData("bs.modal");
}
</script>
5.对于post ajax的统一处理
/**
* jquery的ajax post封装
*/
$.postAjax = function(url,data,callback){
$.ajax({
async : false,
url:url,
type:"post",
dataType:"json",
data:data,
// timeout:6000,
beforeSend : loading_start(),
success:function(msg){
if(msg.hasOwnProperty("code") && -1 == msg.code){//异常的统一处理
$.alert(msg.message);
return;
}
callback(msg);
},
error:errorObj,
complete : loading_end()
});
};