简介

日历

快速登陆

新发表

新评论

新留言

BLOG信息

链接收藏

RSS


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());


2006/4/17 18:03:00

Posted by guanhui | 阅读全文 | 回复(0) | 引用通告 | 编辑 | 收藏该日志

发表评论:

    昵称:
    密码:
    主页:
    标题: