Good day, I have a problem with my code, im a student testing things with servlets and stuff.
the following code is a class which handles querry in a database. I like to put this to a separate class so
that i can reuse this code. the problem is when i Try to test my code, it throws a
NullPointerException. it may sound like a newbie question but can I pass the Statement Object
to JSP or other classes
this is where I try to re-use the previous code
well it compiled without errors but when i tried to run it, it
throws NullPointerException. Is my Idea possible? Did I forget
Joined: Oct 08, 2006
Apart from the problem, the design is awful. You shouldn´t be storing expensive resources as connection, statement and resultset as an instance variable. You should be acquiring and closing them in the shortest possible scope. You should map the results of interest to a collection of data transfer objects and use it instead. Lookup the DAO pattern.
Regarding to the NullPointerException: well, just read the stacktrace. The line number of the 1st line points to the line where it is been caused. Lookup that line in your code and find out which object references are possibly null while it is been accessed/invoked. If found, fix it accordingly by just instantiating it or by adding a nullcheck.
Led Estonilo wrote:
seperate java.servlet.* and java.sql.* and create two seperate class which handles different jobs?
Your classes that interact directly with the database should not require a servlet container to run.
You should be able to test them from the command line, or from test scripts.
Down the road, you should be able to re-use them from a non-web interface without having to change them.
Likewise, your web classes, (servlets, filters, JSPs, listeners, etc) should not need to import any of the java.sql classes or packages.
If you're looking into DAO as Bauke Scholtz suggested, you will learn how to do this.