【发布时间】:2014-03-06 19:49:45
【问题描述】:
这是我的 javascript 部分
<script language=javascript type="text/javascript">
function myFunction() {
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/Test/Servlet");
request.send();
//document.write("Request GET enviado!");
}
</script>
这是我的 doGET 部分
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Request GET recebido!");
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/Tests";
// Database credentials
String USER = "fabio";
String PASS = "hacking";
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM people";
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body>");
// Extract data from result set
while (rs.next()) {
//Retrieve by column name
int person_id = rs.getInt("person_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
//Display values
out.println("Person ID: " + person_id + " | ");
out.println("First name: " + first_name + " | ");
out.println("Last name: " + last_name + "<br>");
}
out.println("</body></html>");
// Clean-up environment
out.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
它们一直工作到从数据库中检索到数据为止。不起作用的部分是将 out.println 发布回 HTML 页面。有人可以建议吗?
谢谢,
【问题讨论】:
-
当你说它不起作用时,会发生什么?
-
页面上什么也不显示。我原以为它会用 DB 中的数据打印一行。
-
它可能会抛出一个异常,该异常只是关闭了输出流。你能检查
catalina.out的堆栈跟踪/错误并发布任何相关的内容吗?
标签: javascript html tomcat servlets