最近在做一个小系统,在尝试用Struts2框架下用Ajax技术进行异步刷新。主要配置如下:
Struts的配置文件:
<package name="ajax" namespace="/" extends="json-default">
<action name="userJSONAction_*" method="{1}" class="userAction">
<result type="json">
<param name="includeProperties">
message,list.*
</param>
</result>
</action>
</package>
第一次,尝试直接返回一个list
后台action的代码
List<VoteSubitem> darenList;
public List<DarenShow> getList() {
return list;
}
action(){
darenList = new ArrayList<VoteSubitem>();
darenList = voteSubitemService.findByVoteName("达人秀")
}
报错,报错,好像是缺少包,就把 commons-beanutils-1.7.0.jar、commons-lang.jar、ezmorph-1.0.3.jar 、
还是报错
就尝试用JSONArray 来返回一个字符串也可以,但是加上下面两句话后,还是报错
// JSONArray jsonArray = JSONArray.fromObject(list);
// String json = jsonArray.toString();
报错信息如下:
Method public java.lang.String org.apache.commons.lang.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on net.sf.json.JSONException: There is a cycle in the hierarchy!
The problematic instruction:
----------
==> ${msgs[0][0]} [on line 76, column 25 in org/apache/struts2/dispatcher/error.ftl]
----------
Java backtrace for programmers:
----------
freemarker.template.TemplateModelException: Method public java.lang.String org.apache.commons.lang.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on net.sf.json.JSONException: There is a cycle in the hierarchy!
去网上找了半天,又试验了半天,终于让我找到问题的原因了,因为javabean VoteSubitem 中有关联主表的外键,在json的过程中,会产生来回的调用循环,从而导致了There is a cycle in the hierarchy!的产生,我重新建立了一个新的javabean 然后重新用第一种方法
代码如下:
private List<DarenShow> list;
public List<DarenShow> getList() {
return list;
}
/** 用ajax的方式获取达人信息*/
public String listDaren() throws Exception {
List<VoteSubitem> darenList = new ArrayList<VoteSubitem>();
darenList = voteSubitemService.findByVoteName("达人秀");
System.out.println(darenList.size());
list = new ArrayList<DarenShow>();
for(VoteSubitem v : darenList){
DarenShow ds = new DarenShow();
ds.setName(v.getArticle());
ds.setPhotosrc(v.getFilePath());
ds.setVideosrc(v.getFilePath2());
list.add(ds);
}
Struts的配置文件不变,这样就成功了,希望能够给大家一点点的帮助。