JSP生成XML文档需要设置contectType为text/xml。再一般情况下,contentType的值为text/html,表示生成html文档。JSP代码演示如何从数据库中取出的数据来动态地生成XML文档。数据库为test,表为student。
<%@ page import="java.sql.ResultSet,java.sql.Statement,java.sql.Connection,java.sql.DriverManager"%>
<%@ page contentType="text/xml;charset=UTF-8" language="java"%>
<?xml version="1.0" encoding="GB2312"?>
<students>
<%
try
{
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&characterEncoding=GBK");
Statement stat = con.createStatement();
String sql = null;
sql = "select * from student;";
ResultSet result = stat.executeQuery(sql);
while(result.next())
{
%>
<student>
<sid><%=result.getString(1)%></sid>
<name><%=result.getString(2)%></name>
<gender><%=result.getString(3)%></gender>
<age><%=result.getString(4)%></age>
<grade><%=result.getString(5)%></grade>
<major><%=result.getString(6)%></major>
</student>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<%@ page import="java.sql.ResultSet,java.sql.Statement,java.sql.Connection,java.sql.DriverManager"%>
<%@ page contentType="text/xml;charset=UTF-8" language="java"%>
<?xml version="1.0" encoding="GB2312"?>
<students>
<%
try
{
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&characterEncoding=GBK");
Statement stat = con.createStatement();
String sql = null;
sql = "select * from student;";
ResultSet result = stat.executeQuery(sql);
while(result.next())
{
%>
<student>
<sid><%=result.getString(1)%></sid>
<name><%=result.getString(2)%></name>
<gender><%=result.getString(3)%></gender>
<age><%=result.getString(4)%></age>
<grade><%=result.getString(5)%></grade>
<major><%=result.getString(6)%></major>
</student>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>