Struts2与XML(dom4j)开发

struts2.xml配置
<action name="getXmlAction" class="com.test.action.xml.GetXmlAction"></action>

action对象:
package com.test.action.xml;

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 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 {
Person person1 = new Person();
person1.setId(1);
person1.setName("张三");
person1.setAge(20);

Person person2 = new Person();
person2.setId(2);
person2.setName("lisi");
person2.setAge(30);

Document document = DocumentHelper.createDocument();

Element rootElement = document.addElement("user");

rootElement.addComment("This is comment");

Element userElement = rootElement.addElement("user");

Element idElement = userElement.addElement("id");
Element nameElement = userElement.addElement("name");
Element ageElement = userElement.addElement("age");

if("张三".equals(this.name)){
idElement.setText(person1.getId() + "");
nameElement.setText(person1.getName());
ageElement.setText(person1.getAge()+"");
}else{
idElement.setText(person2.getId() + "");
nameElement.setText(person2.getName());
ageElement.setText(person2.getAge()+"");
}

HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/xml; charset=utf-8");
response.setHeader("cache-Control", "no-cache");

PrintWriter out = response.getWriter();

OutputFormat format = OutputFormat.createPrettyPrint();

format.setEncoding("utf-8");

XMLWriter write = new XMLWriter(out,format);
write.write(document);

out.flush();
out.close();


return null;
}
}


package com.test.action.xml;

public class Person {

private int id;
private String name;
private int age;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

你可能感兴趣的:(struts2)