Struts2与EasyUI整合时,对于Exception异常的处理,返回含错误信息的JSON字符串

一、背景

既然使用了EasyUI那么,基本上都是通过JSON来进行数据交换。那么问题就来了,struts2可以通过配置,发生异常时,可以转发到相应错误页面,并显示错误信息。我们不需要返回错误页面啊!那如何返回一个JSON字符串呢?

struts.xml配置文件:

    <package name="xxx-default" extends="json-default">
        <global-results>
            <result name="error">/WEB-INF/jsp/common/error.jsp</result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping result="error" exception="java.lang.Exception">
            </exception-mapping>
        </global-exception-mappings>
    </package>

 用户列表JSP页面:

<table id="user_dg" class="easyui-datagrid"
	data-options="url:'${pageContext.request.contextPath}/user_list.do',
        fit:true,
        rownumbers:true,
        toolbar:'#user_toolbar',
        singleSelect:true,
        pagination:true,
        pageSize:20,
        loadFilter:function(result){ 
                    if(!result.rows||!result.total){ 
                        if(result.errorMsg){  
                            $.messager.alert('错误提示','获取用户列表信息失败!错误原因:<br/>'+result.errorMsg,'error');  
                        }else{  
                            $.messager.alert('错误提示','获取用户列表信息失败!','error');  
                        }  
                        return {total:0,rows:[]};  
                    }else{
                        return result;
                    }
                }">
	<thead>
		<tr>
			<th data-options="field:'id',width:50">id</th>
			<th data-options="field:'username',width:150,sortable:true">用户名</th>
			<th data-options="field:'name',width:150,sortable:true">姓名</th>
			<th data-options="field:'email',width:200">邮箱地址</th>
			<th data-options="field:'mobile',width:200">手机</th>
			<th data-options="field:'birthday',width:150,sortable:true">生日</th>
			<th data-options="field:'options',width:150">操作</th>
		</tr>
	</thead>
</table>

如果没有异常那么正常返回的JSON字符串格式为{"total":总共记录数,"rows",[{用户信息1},{用户信息2}...]}

用户信息中的JSON字段名称与th 的  data-options="field:'字段名'..   一致

原先可能你会这么写错误页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
	错误信息:
	<s:property value="exception.message" />
</body>
</html>

二、思路

思路其实很简单,指定的错误页面是JSP,那么我们可以让JSP页面显示JSON字符串不就行了么。

 

二、实施

有了,思路就要实施了,现在你只需要让错误页面,返回一个包含错误信息的JSON字符串

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
{"errorMsg":"<s:property value="exception.message" />"}

来试试看,故意抛出个异常,

    /**
     * 用户列表JSON
     * 
     * @return
     */
    public String list() throws Exception {
        dataMap.clear();
        // 故意抛出个异常,看看是否凑效
        if (true)
            throw new HibernateException(new RuntimeException(new Exception("[这是异常啊!!!!}\"..._}]")));
        int total = userService.countAll();
        Collection<User> users = userService.findPageByHQLQuery(
                getStartIndex(), getPageSize());
        log.debug("用户数:" + total);
        dataMap.put("total", total);
        // 过滤集合中元素的属性
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerPropertyExclusions(User.class, new String[] {
                "roles", "OPTIONS" });
        dataMap.put("rows", JSONArray.fromObject(users, jsonConfig));
        return "list";
    }



 

可以显示错误信息,OK,这样就搞定了,O(∩_∩)O~

注释掉看看原来的信息能不能正常显示,:

//if (true)
//            throw new HibernateException(new RuntimeException(new //Exception("[这是异常啊!!!!}\"..._}]")));

 

 还好可以正常显示。。。O(∩_∩)O~

我这边对异常信息处理比较粗糙,而且错误信息也不够友好,用户看到的话,肯定不知道是什么意思,这是问题所在,大家如果有什么更好的方法,更优雅的方法,让struts2处理异常信息,而且这个信息能够比较友好的,请赐教,欢迎讨论。。。

猜你喜欢

转载自jaychang.iteye.com/blog/2075206