我使用Tomcat 8.0服務器,數據庫,H2和IntelliJ IDEA 14我WebApplication的,但是當我運行的應用程序(按鈕事件)我收到我收到顯示java.lang.NullPointerException在IntelliJ IDEA的和Tomcat
的Java。 lang.NullPointerException image. 我有(它已經測試)這樣的成功連接到數據庫:
public class DbConnection {
private static final String DRIVER = "org.h2.Driver";
private static final String URL = "jdbc:h2:tcp://localhost/~/Students";
private static final String USER_NAME = "doncho";
private static final String PASS = "";
private static DbConnection instance;
private static Connection conn;
private DbConnection(){
}
public static DbConnection getInstance(){
if(instance == null){
instance = new DbConnection();
}
return instance;
}
public Connection getConnect() throws SQLException{
Connect();
return conn;
}
private void Connect() throws SQLException {
if (conn == null) {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Driver isn't found");
e.printStackTrace();
}
DriverManager.getConnection(URL, USER_NAME, PASS);
}
}
public void Disconnect() throws SQLException{
if(conn != null){
conn.close();
conn=null;
}
}
我已創建類RegisterDao
必須名稱爲「名」將數據插入表剛一列 - 「名」
public class RegisterDAO {
Connection conn = null;
PreparedStatement state = null;
public StudentBean registerStudent(String userName) throws SQLException{
StudentBean result = null;
String sql = "INSERT INTO Name VALUES(?)";
try {
conn = DbConnection.getInstance().getConnect();
state = conn.prepareStatement(sql);
state.setString(1, userName);
state.execute();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(state != null){
state.close();
}
}
DbConnection.getInstance().Disconnect();
return result;
}}
這是我的課(的Java bean)StudentBean
@javax.ejb.Stateless(name = "StudentEJB")
public class StudentBean {
private String name;
public StudentBean() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
我用thеsе類通過servlet來插入表 「名稱」 數據 - RegisterServlet
public class RegisterServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Connection conn = DbConnection.getInstance().getConnect();
System.out.println("It Works");
} catch (SQLException e) {
e.printStackTrace();
}
String username = request.getParameter("usernameReg");
StudentBean student;
try {
student = new RegisterDAO().registerStudent(username);
request.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
try {
DbConnection.getInstance().Disconnect();
} catch (SQLException e) {
e.printStackTrace();
}
}}
但我得到上面的錯誤。我很困惑,因爲我在Eclipse中測試了源代碼,並且它在那裏工作,但是在IntelliJ中沒有。 我是IntelliJ新手,所以我希望有更多經驗的人會給我一個解決問題的想法。
P.S.來自servlet的System.out.println("It Works");
工作,我保證我調用servlet到「index.jsp」正確。
對不起,對這篇長文章和最好的問候, D.Balamjiev。
錯誤是我的。我忘了設置連接初始化。感謝您的幫助,現在工作正常。 –