struts2 Action里直接输出 dom4j的使用

在使用Ajax与Action交互时,可以直接在Action里输出,而不是转发给JSP.struts.xml中声明action时,不再需要result标签


package com.struts2;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.opensymphony.xwork2.ActionSupport;

public class GetXMLAction extends ActionSupport {
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		People people=new People();
		people.setId(1);
		people.setName("zhangsan");
		people.setAddress("beijing");
		people.setAge(20);
		
		People people2=new People();
		people2.setId(2);
		people2.setName("lisi");
		people2.setAge(30);
		people2.setAddress("Hangzhou");
		
		//下面都是dom4j的使用方法,还是挺简单的
		org.dom4j.Document document=DocumentHelper.createDocument();
		
		Element rootElement=document.addElement("persons");
		
		rootElement.addComment("This is comment!!");
		Element e=rootElement.addElement("person");
		Element idElement=e.addElement("id");
		Element nameElement=e.addElement("name");
		Element ageElement=e.addElement("age");
		Element addressElement=e.addElement("address");
		
		if(name.equals("zhangsan"))
		{
			idElement.setText(String.valueOf(people.getId()));
			nameElement.setText(people.getName());
			ageElement.setText(String.valueOf(people.getAge()));
			addressElement.setText(people.getAddress());
		}else if(name.equals("lisi"))
		{
			idElement.setText(String.valueOf(people2.getId()));
			nameElement.setText(people2.getName());
			ageElement.setText(String.valueOf(people2.getAge()));
			addressElement.setText(people2.getAddress());
		}
		
		//取HttpServletResponse对象,直接输出
		HttpServletResponse resp=ServletActionContext.getResponse();
		resp.setContentType("text/xml;charset=utf-8");
		resp.setHeader("cache-control", "no-cache");
		PrintWriter out=resp.getWriter();
		OutputFormat format=OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter writer=new XMLWriter(out, format);
		writer.write(document);
		out.flush();
		out.close();
		//返回值可以随意,因为不再判断
		return null;
	}
}

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记