aspose file tools*
The moose likes Servlets and the fly likes NullPointerException At Statement stmt = conn.createStatement(); Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "NullPointerException At Statement stmt = conn.createStatement();" Watch "NullPointerException At Statement stmt = conn.createStatement();" New topic
Author

NullPointerException At Statement stmt = conn.createStatement();

JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
I am trying to use a connection pool to retrieve
data from a database. I have succeeded in putting InitialContext, DataSource, Statement,
ResultSet in "one servlet". And I am able to display the output in the browser. It means that the table is created in the database, the connection pool is properly configured, DataSource is referenced in the web.xml, and mapping in the web.xml has been taken care of.
I ran into problem when I tried to put
IntialContext and DataSource in one class
(DBConnection.java) that specializes in providing Connection object (conn). And another class
(VerificationServlet.java) with Statement and
ResultSet in it references the provided Connection object. (DBConnection.java and VerificationServlet.java are in a package 'cptest'.)
The error message I got is
"java.lang.NullPointerException at
cptest.VerificationServlet.doGet(VerificationServlet.java:25)
and the 25th line of the VerificationServlet is
Statement stmt = conn.createStatement();
I am lost. I do not know what went wrong.
DBConnection.java
VerificationServlet.java

[ July 11, 2003: Message edited by: JiaPei Jen ]
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

It looks like you've forgotten to get the Connection from the DataSource.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Oops, my bad.
What happens if conn = ds.getConnection() throws an exception? You aren't even checking for it.
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
The exception is caught in the code snippet shown below:

Somehow, the Connection (conn) is not passed from DBConnection.java to VerificationServlet.java. Just cannot figure out what wrong with my code.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

If an exception is thrown, you hide the exception and return null. Are you sure there is no exception being thrown?
This would cause a NullPointer every time.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: NullPointerException At Statement stmt = conn.createStatement();