创建统一返回的json对象
public class AjaxResponse{
/**}
/**
* AJAX请求状态返回值
*/
public enum EnumAjaxResponseStatus {
/** 成功 **/
SUCCESS(0),
/** 失败 **/
FAIL(-1),
/** 网络异常 **/
NETERROR(-9);
private int status;
private EnumAjaxResponseStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
------------------------------------------------
自定义异常类
public class PermissionException extends RuntimeException {
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
*
* 描述:要一引入codehaus依赖
*
* 作者: dlj
* 时间: 2018年1月16日 上午9:22:45
*
*/
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// config
objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}
public static
if (src == null) {
return null;
}
try {
return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
} catch (Exception e) {
logger.warn("parse object to String exception, error:{}", e);
return null;
}
}
public static
if (src == null || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
} catch (Exception e) {
logger.warn("parse String to Object exception, String:{}, TypeReference
return null;
}
}
public static Map
if(obj == null)
return null;
Map
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}
}
------------------------------------------------
异常处理器
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mv;
String defaultMsg = "System error";
// 转成springmvc底层对象(就是对action方法的封装对象,只有一个方法)
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 取出方法
Method method = handlerMethod.getMethod();
// 判断方法是否返回json
// 只要方法上有responsebody注解表示返回json
// 查询method是否有responsebody注解
ResponseBody responseBody = AnnotationUtils.findAnnotation(method,
ResponseBody.class);
JsonData resolveExceptionCustom = resolveExceptionCustom(ex,request,method);
if (responseBody != null) {
// 将异常信息转json输出
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setAttributesMap(resolveExceptionCustom.toMap());
mv = new ModelAndView();
mv.setView(view);
}else{
mv = new ModelAndView("error/exception", resolveExceptionCustom.toMap());//exception为jsp页面名
}
return mv;
}
// 异常信息解析方法
private JsonData resolveExceptionCustom(Exception ex,HttpServletRequest request,Method method) {
JsonData resultInfo = null;
String url = request.getRequestURL().toString();
Map
if (ex instanceof PermissionException) {
// 抛出的是系统自定义异常
resultInfo = ((PermissionException) ex).getJsonData();
} else {
// 重新构造“未知错误”异常
resultInfo = JsonData.fail("未知错误!",1);
log.error("unknown exception, url:{},ex:{} method:{} parameterMap:{}," , url, ex,method.getName(),JsonMapper.obj2String(parameterMap));
}
return resultInfo;
}
}
-----------------------------------------
spring中添加配置