日期:2014-05-17 浏览次数:20782 次
package json;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class xmljson extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String name = req.getParameter("name");
Gbean g = new Gbean();
if(name.equals("zhangsan"))
{
g.setName("zhangsan");
g.setAge(20);
}
else
{
g.setName("lishi");
g.setAge(30);
}
Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("users");
document.add(root);
root.addComment("This is a xml!");
Element n = DocumentHelper.createElement("name");
root.add(n);
Element a = DocumentHelper.createElement("age");
root.add(a);
n.setText(g.getName());
a.setText(String.valueOf(g.getAge()));
OutputFormat format = OutputFormat.createPrettyPrint();
//传输xml时要设置类型
resp.setContentType("text/xml,charset=utf-8");
//阻止浏览器的缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
PrintWriter out = resp.getWriter();
XMLWriter xmlWriter = new XMLWriter(out,format);
xmlWriter.write(document);
out.flush();
}
}