0
現在、私は仕事と呼ばれるjavaオブジェクトを持っています、そのオブジェクトは、その中にこのメソッドを持っています。ヌルポインタ例外を与えるDBに接続するメソッド
public void Connection(Connection conn) throws NamingException, SQLException {
// Setup the Database datasource
Context ctx = new InitialContext();
Context env = (Context) ctx.lookup("java:comp/env");
DataSource ds = (DataSource) env.lookup("jdbc/carRentalSystem");
conn = ds.getConnection();
}
このメソッドをサーブレット内で呼び出して、DBに接続してテーブル行を追加します。どんな理由であれ、私はデバッグを通してそれを実行するときにヌルポインタ例外を得続けます。これを正しく動作させる方法を教えてもらえますか?
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// Obtain submitted form data
Work work = new Work();
String firstName = req.getParameter("First_Name");
String lastName = req.getParameter("Last_Name");
String username = req.getParameter("User_Name");
String email = req.getParameter("Email_Address");
String password = req.getParameter("Password");
ResultSet rs = null;
Connection conn = null;
Statement st = null;
try {
work.Connection(conn);
// Prepare the SQL statmenet to insert the values
PreparedStatement stmt = conn.prepareStatement("INSERT INTO userdetails(First_Name, Last_Name, Email_Address, Password, User_Name) VALUES (?,?,?,?,?)");
stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setString(3, email);
stmt.setString(4, password);
stmt.setString(5, username);
// Execute the insert
stmt.executeUpdate();
conn.close();
// Dispatch into success page
RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
requestDispatcher.forward(req, res);
} catch (Exception e) {
work.ErrorHome(req, res, e);
} finally {
try {
if (st != null)
st.close();
} catch (java.sql.SQLException e) {
}
try {
if (conn != null)
conn.close();
} catch (java.sql.SQLException e) {
}
try {
if (rs != null)
rs.close();
} catch (java.sql.SQLException e) {
}
}
}
}
stacktraceをヘルプに追加 – BoBasket4
NullPointerExceptionがどこに届いているのか、Stacktraceを投稿して通知するのはなぜですか?それは私が本当にこれが典型的なNPEとは違うことを本当に疑っているので、おそらく複写物として閉じられるでしょう。 –
メソッド 'public void Connection(Connection conn)'をあなた自身で作成しましたか?なぜなら、[Javaは常に値で渡される](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value)のために動作しないからです。作成した接続を返し、その戻り値で作業する必要があります。 –