基本上,我的 Web 应用程序中有两个类,一个类“FormProcess.java”,它将信息插入 HTML 表单,执行一些计算,然后将结果输出为 HTML。这绝对没问题。
我还有一个用于将数据添加到 MySQL 数据库的新行中的类,该类称为“SqlConnect.java”。如果我在服务器上单独运行它(即它正确地在表上插入一行),这也可以正常工作。
我正在努力使 SqlConnect 方法从 FormProcess 类运行。当我将以下内容添加到 FormProcess 时:
private SqlConnect sql;
并在一个方法中:
sql.doPost(request, response);
我收到以下错误:
java.lang.NullPointerException
crunch.FormProcess.doGet(FormProcess.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
这是目前的 SqlConnect 类(我省略了导入等):
@WebServlet(name="sql",urlPatterns={"/sql"})
public class SqlConnect extends javax.servlet.http.HttpServlet {
FormProcess process = new FormProcess();
private static final long serialVersionUID = 1L;
public SqlConnect() {
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
public void performTask(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
testJndiDataSource();
}
public void testJndiDataSource() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/CrunchDB");
conn = ds.getConnection();
st = conn.createStatement();
st.executeUpdate("INSERT INTO log " + "VALUES (20, '1', '1', " + process.salaryInt + ", "+ process.takeHomePAYE +", "+ process.takeHomeContractor +", 2)");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
我确信有一种简单的方法可以做到这一点,我只是无法解决,正如我所说的 SqlConnect 类将自行运行良好。
干杯