AJAX編程技巧:在Struts Action中如何向客戶端發送xml文件?

在AJAX中,數據傳遞都是通過xml格式,在struts中,我們就需要在action中生成xml格式的文件傳遞到客戶端,再由客戶端js進行解析,下面的代碼就是在action中生成xml格式文件的:
假如我們需要將如下格式的xml文件傳遞爲客戶端:
<entity>
<row>
<field name="id" value="1"/>
<field name="username" value="張三"/>
</row>
<row>
<field name="id" value="2"/>
<field name="username" value="李四"/>
</row>
</entity>
而這些數據存儲在數據庫中,有兩個字段,id和name,則在action中:


首先,獲取數據庫中的數據:
ArrayList myList = new ArrayList();
Userinfo userinfo = new Userinfo();
myList = userinfo.select();


然後,使用jdom生成xml格式的文件流:
Element root = new Element("entity");
Iterator it = myList.iterator();
while (it.hasNext()) {
UserinfoSelectActionBean bean = (UserinfoSelectActionBean) it
.next();
Element row = new Element("row");
Element fieldId = new Element("field");
fieldId.setAttribute("name", "id");
fieldId.setAttribute("value", bean.getId());
row.addContent(fieldId);
Element fieldName = new Element("field");
fieldName.setAttribute("name", "name");
fieldName.setAttribute("value", bean.getName());
row.addContent(fieldName);
root.addContent(row);
}


接着,先把數據格式成爲中文格式,就可以通過jdom的方法輸出了:


Document doc = new Document(root);
response.setContentType("application/xml;charset=GB2312");
Format format = Format.getPrettyFormat();
format.setEncoding("GB2312");
XMLOutputter outer = new XMLOutputter(format);
outer.output(doc, response.getWriter());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章