81,091
社区成员
发帖
与我相关
我的任务
分享
public String managerLogOut() {
try {
..........
result = JsonPack.mapToJsonData(rtnMap);
} catch (Exception e) {
result = JsonPack.exceptionToJson(e);
}
}
public static String exceptionToJson(Throwable e) {
JSONObject jsonData = new JSONObject();
jsonData.put(CommonConstant.JSON_LIST_RESULT_CODE,CommonConstant.JSON_LIST_RESULT_FAIL);
logger.error("系统内部异常", e);
jsonData.put(CommonConstant.ITEM_RSPCODE, ErrCode.SYSTEM_ERROR);
jsonData.put(CommonConstant.ITEM_RSPMSG, ErrDeal.getErrMsg(ErrCode.SYSTEM_ERROR));
jsonData.put(CommonConstant.JSON_LIST_MSG, ErrDeal.getErrMsg(ErrCode.SYSTEM_ERROR));
return jsonData.toString();
}
intercept method:
if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("x-requested-with"))) {
response.setContentType("application/x-json; charset=utf-8");
try {
return invocation.invoke();
} catch (Exception e) {
e.printStackTrace();
JSONObject returnObj = new JSONObject();
returnObj.put("results", new JSONArray());
returnObj.put("success", false);
returnObj.put("errorMsg", e.getMessage());
response.getWriter().print(returnObj);
return null;
}
} else {
return invocation.invoke();
}
将拦截器配置到defaultStack之后,也就是让自己写的这个拦截器去拦截由ajax产生的exception
II.在自己的Action中去写自己需要实现的功能模块,如果需要使用ajax的话,则按如下模式进行编码
// 进行自己的操作,然后得到结果result
response.setContentType("application/x-json; charset=utf-8");
JSONObject returnObj = new JSONObject();
returnObj.put("results", result);
returnObj.put("success", true);
response.getWriter().print(returnObj);
return NONE;
III.在JS中得到结果
/* 回调函数
1. 得到rsponseText
2. 将responseText转换为JSON对象:json
*/
if(json.success){
// 进行正确的操作:json.results
}else{
alert(json.errorMsg);
}