Action:(GetXmlAction)
package org.viancent.action; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.viancent.domain.Person; import com.opensymphony.xwork2.ActionSupport; public class GetInfoAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; // 此属性用于接收页面的数据信息进行判断 返回结果 public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String execute() throws Exception { // create new person // zhangsan Person person1 = new Person(); person1.setPid(1); person1.setPname("zhangsan"); person1.setPage(20); person1.setAddress("武汉"); // lisi Person person2 = new Person(); person2.setPid(2); person2.setPname("lisi"); person2.setPage(30); person2.setAddress("上海"); // create new XmlObject use dom4j // 1.get document by documenthelper Document document = DocumentHelper.createDocument(); // create a comment document.addComment("This is a Xml!"); // create root Element Element rootElement = document.addElement("Users"); // create child Element by root Element Element childElement = rootElement.addElement("User"); // create id Element by child Element Element idElement = childElement.addElement("id"); // create name Element by child Element Element nameElement = childElement.addElement("name"); // create age Element by child Element Element ageElement = childElement.addElement("age"); // create address Element by child Element Element addressElement = childElement.addElement("address"); // check name if ("zhangsan".equals(this.getName())) { idElement.setText(person1.getPid() + ""); nameElement.setText(person1.getPname()); ageElement.setText(person1.getPage() + ""); addressElement.setText(person1.getAddress()); } else { idElement.setText(person2.getPid() + ""); nameElement.setText(person2.getPname()); ageElement.setText(person2.getPage() + ""); addressElement.setText(person2.getAddress()); } // use XMLWriter and HttpServletResponse // get HttpServletResponse HttpServletResponse response = ServletActionContext.getResponse(); // 设置返回文本的类型 response.setContentType("text/xml ; charset=utf-8"); /* * 这里一定要设定ContentType,不然客户端无法辨识服务端的发送的信息类型。 */ response.setHeader("Cache-Control", "no-cache"); /* * 设定不需要缓存 */ // get PrintWriter PrintWriter out = response.getWriter(); // 创建排版规则 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8");// 设置xml文档的编码格式 // 开始写入数据信息 XMLWriter writer = new XMLWriter(out, format); // 通过XmlWriter的构造函数,将Xml文档对象写入到PrintWriter中,实现返回 writer.write(document); // 清空流 out.flush(); // 关闭流 out.close(); return null;// 因为是使用jquery进行的异步提交,所以不需要进行跳转 } }Struts2+jQuery+Dom4j实现服务器返回Xml文档(2)
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/55edc11501a11b451d9146254c9173d7.html