我是学习 JSP 和 Servlet 的新手。我有一个 Java 类,它调用一个存储过程并从数据库返回一个状态列表(这是我学习时的测试用例,其他更复杂的操作稍后会出现)。状态列表应该返回到 JSP 以在表单中显示/使用,等等。现在,我很高兴通过 JSP 页面打印数据以知道它在那里。
但是,当我从 JSP 调用 Java 代码时,结果对象似乎返回为 null,因此无法访问任何数据。我也尝试将数据作为 ResultSet 对象返回,但结果是一样的。我确实知道从 SQL 调用存储过程时有效。此外,我将 Java 代码作为响应 doPost 请求的 servlet 并且工作正常......
我可能会错过/无法理解什么?这可能吗?
package edu.XXXX.ais.userapp;
import java.sql.*;
import java.util.*;
public class DBQueries {
public static Vector<String> getStatesList() {
Vector<String> results = new Vector<String>();
Connection con = null;
try {
// Example of executing a stored procedure
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection ("jdbc:mysql://hostname:3306/dbName","username","password");
CallableStatement cs = con.prepareCall("{call getStatesList()}");
ResultSet rs = cs.getResultSet();
while (rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
System.err.println("Servlet could not display records." + e);
} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found." + e);
} finally {
try {
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
System.err.println(e);
}
}
return results;
}
}
调用上述Java代码的JSP页面(期望能收到结果...)
<html>
<head>
<title>Foo</title>
</head>
<body>
<h3>List of states via a servlet call to the database</h3>
<%@ page import="java.util.*" %>
<%@ page import="edu.XXXX.ais.userapp.DBQueries" %>
<%
Vector rs = DBQueries.getStatesList();
if (rs != null)
for (int index = 0; index < rs.size(); index++) {
out.println("Name : " + (String) rs.get(index));
}
%>
</body>
</html>
产生的Tomcat错误如下:
org.apache.jasper.JasperException: An exception occurred processing JSP page /states.jsp at line 12
9: <%@ page import="edu.XXXX.ais.userapp.DBQueries" %>
10:
11: <%
12: Vector rs = DBQueries.getStatesList();
13: if (rs != null)
14: for (int index = 0; index < rs.size(); index++) {
15: out.println("Name : " + (String) rs.get(index));
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
edu.XXXX.ais.userapp.DBQueries.getStatesList(Unknown Source)
org.apache.jsp.states_jsp._jspService(states_jsp.java:75)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)