在Struts2下使用ExtJs、Jquery、Dojo、DWR等AJAX框架,一般和页面ajax交互传递的数据格式是xml和json字符串,如何在页面获取这些数据呢?
常用以下两种方法:
方法I:写入输出流
action代码块
PrintWriter out = null;
// 方案I:把输出的json字符串/xml写入输出流,让页面直接获得数据,return null
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
out = ServletActionContext.getResponse().getWriter();
out.print(treeNodeJson); // treeNodeJson就是拼装的json或xml
out.close();
return null
注意:
struts2的action return null,不需要返回页面了,因为执行了该action方法直接就可以从页面out对象获取数据了。
js代码块:
proxy : new Ext.data.HttpProxy({
url : '${ctx}/getSectionListForSend.action'
})
这里不需要指明获取对象是 treeNodeJson ,因为它已经是二进制数据流里面的对象了,只需要读取里面的数据即可。
方法二:写入文件
ajax需要获取数据,这时候数据是存在在文件中得-----而数据文件就是action return的那个jsp文件;
因此,第二种方式有个典型的特点就是:action必须有返回值,指定返回页面,返回页面拼装xml或者是json字符串。
action代码块:
public String checkBatchSendSectionInfo(){
msg = "查询失败...";
try{
if(batchNo == null || "".equals(batchNo) ){
logger.error("批号为空。。。");
}
batchSendDtoList=batchPgManager.getSendInfoByBatchNo(batchNo);
totalSize=batchSendDtoList.size();
}catch(Exception e){
e.printStackTrace();
logger.error("查看批次发送给地方的信息出错!");
}
msg = "查询成功...";
return SUCCESS;
}
struts.xml
<action name="getTitleSendList" class="titleSendAction" method="checkBatchSendSectionInfo">
<result>/pages/titleSend/xml_sendTitle.jsp</result>
</action>
jsp片段:
<?xml version="1.0" encoding="utf-8"?>
<%@ page language="java" contentType="text/xml;charset=utf-8" %>
<%@ include file="/common/taglibs.jsp"%>
<dataset>
<s:if test="%{batchPgList!=null}">
<results><s:property value="totalSize" /></results>
<s:iterator value="batchPgList" status="sts">
<row>
<id><s:property value="id" /></id>
<batchNo><s:property value="batchNo" /></batchNo>
<recSectCode><s:property value="recSectCode" /></recSectCode>
<batchSts><s:property value="batchSts" /></batchSts>
<senderId><s:property value="senderId" /></senderId>
<senderName><s:property value="sender.nameCn"/></senderName>
<sendTime><s:date name="sendTime" format="yyyy-MM-dd HH:mm:ss"/></sendTime>
<receiverName><s:property value="receiverName"/></receiverName>
<receiveTime><s:property value="receiveTime"/></receiveTime>
<receiveResult><s:property value="receiveResult"/></receiveResult>
</row>
</s:iterator>
</s:if>
</dataset>
js片段
var batchStore = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : '${ctx}/checkBatchSendSectionInfo.action'
}),
reader : new Ext.data.XmlReader({
record : 'row',
id : 'id',
totalRecords : 'results'
},['id','batchNo','recSectCode','batchSts','senderId','senderName','sendTime',
'receiveName','receiveTime','receiverResult'])
});
batchStore.load({
params : {
'start' : 0,
'limit' : pgSize
}
});
仔细看我标注为红色的部分,这是数据从action传递到页面(放在request范围内的数据),页面重新解析拼装为xml,js页面获取xml的数据(注意是通过xml内的标签名获取的!!!此时跟action内的数据名称没关系的,是解析后的数据)
是不是感觉有点复杂呀??其实这个因为xml是层级结构的数据,所以需要解析重组的,如果是json字符串,就简单多拉。
jsp代码块
<?xml version="1.0" encoding="utf-8"?>
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="batchPgList" escape="false"/>
这时候直接从js中获取数据就好,跟第一种方式写入输出流一样。