init() does not fire
Hello,
It seems that init() does not fire, thus my connection is never established. I cannot figure out why
Here is the updated servlet code:
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletResponse;
publicclass CustomQueryextends HttpServlet
{
Connection con;
Statement stmt;//this is where stmt is declared
ResultSet rs;
String dbDriver;
BufferedReader fileRead;
publicvoid init()throws ServletException
{
try
{
dbDriver ="";
String dbUrl ="";
String dbName ="";
String dbUser ="";
String dbPassword ="";
String newLine ="";
fileRead =new BufferedReader(new FileReader("connection.txt"));
boolean readerStatus = fileRead.ready();
newLine = fileRead.readLine();
while (readerStatus)
{
StringTokenizer st =new StringTokenizer(newLine,",");
while (st.hasMoreTokens())
{
dbDriver = st.nextToken();
dbUrl = st.nextToken();
dbName = st.nextToken();
dbUser = st.nextToken();
dbPassword = st.nextToken();
}
readerStatus = fileRead.ready();
}
Class.forName(dbDriver);
String url = dbUrl + dbName;
con = DriverManager.getConnection(url, dbUser, dbPassword);
//System.out.print(url + "\n");
//System.out.println(dbUser + "\n");
//System.out.println(dbPassword + "\n");
}
catch (IOException ioex)
{
ioex.printStackTrace();
}
catch (SQLException sqlex)
{
sqlex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
doPost(request, response);
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter printer = response.getWriter();
printer.println(dbDriver);
}
}
Server and web.xml files can be downloaded from pcwebs.ca/pf/server.xml and pcwebs.ca/pf/web.xml
note: as i understand because of the way my server and web.xml (web.xml in the conf directory not web-inf directory) are, all i have to do to deploy is stop the server put my newly compiled class into the installdir/\webapps\ROOT\WEB-INF\classes start the server and access it by http://localhost/servler/ClassName
using Tomcat 4.1
[4491 byte] By [
paulchwda] at [2007-11-26 20:56:47]

# 1
You're carrying quite a duke star debt to users who have helped you previously. Pay them up and we'll talk.
# 2
My apologizes, im new to this forum. I will make things right
# 3
No problem. ;)Remember, init() isn't called until a servlet is loaded. Usually, a servlet isn't loaded until a request is made against it. What happens when you point your web browser to your servlet?
# 4
when i had the doPost() method connecting to the DB, it threw a null pointer exception at the line i instantiated my connection.
I remmed out most of doPost() to see if init() was the problem, and it is
When i access the servlet i(now that doPost() only tries to print out a String populated in init() ) Iget a blank page with no HTML in the source
When i recompile i stop the server and restart it.
# 5
Ok, so init() *does* fire.
Tracking down the NPE should be easy enough for you. But in the meantime, you should consider a few things:
Remember, a single instance of a Servlet can service any number of users. Establishing of your database connection should be done in the doPost() method, not in init(). This way, every user gets their own connection. Of course, in situations like this, you should consider connection pooling and using a Servlet DataSource for managing your connections. Remember to *always* close your connections and output streams when you're done using them.
# 6
do it in doPost eh? worth trying...
what do you mean by :
connection pooling and using a Servlet DataSource for managing your connections
I tried writing to a string in inti() and printing that string (it was a global var) in doPost and i got nothing... which makes sense as the NPE was the connection object being null (con was instantiated in init()..thus how i fiugured init() was the culpuret)
any thoughts? .. as i cant see anything in that code other then init() not going to make it null
# 7
> do it in doPost eh? worth trying...
You can load the driver in init(), but get the connection in doPost().
> what do you mean by :
>
> connection pooling and using a Servlet DataSource for
> managing your connections
Google for 'tomcat DataSource'
> I tried writing to a string in inti() and printing
> that string (it was a global var) in doPost and i got
> nothing... which makes sense as the NPE was the
> connection object being null (con was instantiated in
> init()..thus how i fiugured init() was the culpuret)
Then look at the string in the init() method... learn how to use Tomcat's log files.
# 8
i will look at the logs, but i hav tried printing out various values from init, including various strings and the con object. Also i wrote code in init that would cause a run time exception if run, and nothing. For some reason init() does not fire
# 9
This shouldn't be the problem, but:
What happens if you change your init method to
public void init(ServletConfig config) throws ServletException{
super.init(config);
//your code here
}
does it fires now? Just a thought :-s
# 10
still doesnt work.I get a null pointer at the line: stmt = con.createStatement();as con is null as it instantiated in init()(when i print out con it prints null, and its not only con)
# 11
> still doesnt work.> > I get a null pointer at the line: stmt => con.createStatement();> Post your updated code please.
# 12
[nobr]import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletResponse;
public class CustomQuery extends HttpServlet
{
Connection con;
Statement stmt;
ResultSet rs;
String dbDriver;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try
{
dbDriver = "";
String dbUrl = "";
String dbName = "";
String dbUser = "";
String dbPassword = "";
String newLine = "";
BufferedReader fileRead = new BufferedReader(new FileReader("connection.txt"));
boolean readerStatus = fileRead.ready();
newLine = fileRead.readLine();
while (readerStatus)
{
StringTokenizer st = new StringTokenizer(newLine, ",");
while (st.hasMoreTokens())
{
dbDriver = st.nextToken();
dbUrl = st.nextToken();
dbName = st.nextToken();
dbUser = st.nextToken();
dbPassword = st.nextToken();
}
readerStatus = fileRead.ready();
}
Class.forName(dbDriver);
String url = dbUrl + dbName;
con = DriverManager.getConnection(url, dbUser, dbPassword);
//System.out.print(url + "\n");
//System.out.println(dbUser + "\n");
//System.out.println(dbPassword + "\n");
}
catch (IOException ioex)
{
ioex.printStackTrace();
}
catch (SQLException sqlex)
{
sqlex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter printer = response.getWriter();
printer.println(con);
String title = "Result from custom query";
try
{
stmt = con.createStatement();
printer.println("<html><body><font color=black> test </font></body></html>");
rs = stmt.executeQuery("SELECT customerID" +
" FROM customer");
while (rs.next())
{
printer.println("<html> <head><title>" + title + "</title><br><br><table border=\"0\"> <tr><td>"
+ rs.getString(1));
}
}
catch (SQLException sqlx)
{
printer.println("SQL Exception");
sqlx.printStackTrace();
}
}
public void destroy()
{
try
{
rs.close();
stmt.close();
con.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
output:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
at CustomQuery.doPost(CustomQuery.java:100)
at CustomQuery.doGet(CustomQuery.java:83)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:696)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:809)
at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:417)
at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:131)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:696)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:809)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:198)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:144)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:209)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:595)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:432)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:954)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:138)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:595)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:432)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:954)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2459)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:132)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:595)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:118)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:593)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:116)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:593)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:432)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:954)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:126)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:595)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:432)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:954)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:152)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:619)
Apache Tomcat/4.1.34[/nobr]
# 13
Please, try changing
BufferedReader fileRead = new BufferedReader(new FileReader("connection.txt"));
to
BufferedReader fileRead = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/connection.txt")));
See if it works. BTW, as far as i could get here (Netbeans bundled Tomcat 5.5) the runtime exceptions are NOT printed to the log file, but to the standard output of the process that began the server (or at least is what seemed to happen here)
# 14
As I said before, you need to be logging your critical events.
Is your connection.txt file being read? Are all the connection parameters being assigned correctly? Does the Connection ever get instantiated?
Please don't take this the wrong way, but I see a *lot* of things wrong with the code you posted. Servlet specific configuration should be kept in the deployment descriptor, not in an external text file in some arbitrary place in your filesystem. Once you do get the NPE fixed, you'll eventually see your application crash as your database connections leak. Like I said before, connections should be opened (and closed) in the doPost method. You do *not* want to do this in init() or destroy().
I think you're trying to tackle too much at once. You should have a solid grasp of JDBC first. Know how connections work, and how to manage them. From there, go to Servlets. Especially understand the servlet lifecycle and how they are threaded. From there, you can combine what you've learned and move on to container managed DataSources.
Good luck!
# 15
I will look into to this descriptor thing as opposed to the TXT file.
Regarding init() and destroy() the 3 database architects i work with (plus various books from Sun) said to open the connections in init() as to have 1 connection for all the users . that way each time the servlet is requested a connection doesnt have to be opend, as its not a large app.
Thanks for the help, i will post some changes soon
# 16
> I will look into to this descriptor thing as opposed
> to the TXT file.
>
> Regarding init() and destroy() the 3 database
> architects i work with (plus various books from Sun)
> said to open the connections in init() as to have 1
> connection for all the users . that way each time the
> servlet is requested a connection doesnt have to be
> opend, as its not a large app.
Hoooooboy!
What books are you referring to? If you have multiple concurrent users contending for the same connection, you *will* have problems. It sounds to me like your DBA's are concerned with the overhead of opening connections. This is the *exact* reason I suggested using a connection pool above.
# 17
Well, I have to totally agree with bckrispi. I first thought it was just a learning proyect or something, but if you are planning on going live with that code, you better give it up already and spend a few hours reading about datasources and connection pools :-) Believe us, it's for your own safety and to keep you away from a big TON of problems.
# 18
[nobr]Thant I will,
I believe I narrowed it down, init() works, my file read statements do not, which is very puzzling.
I copied the file read code into another class with a main() and ran it with the correct output
When i copied that code into my servlet's init(), and try to print out (in doPost() i print out dbDriver which is a sting that is populated from the txt file and I run it on Apache Tomcat 4.1 null prints out.)
I would like to setup the connection in init() for now, and after getting that to work I will use a more generally accepted way of establishing a connection.
my code :
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletResponse;
public class CustomQueryDebug extends HttpServlet
{
Connection con;
Statement stmt; //this is where stmt is declared
ResultSet rs;
String dbDriver;
BufferedReader fileReader;
public void init() throws ServletException
{
try
{
dbDriver = "";
String dbUrl = "";
String dbName = "";
String dbUser = "";
String dbPassword = "";
String newLine = "";
String test = "";
fileReader = new BufferedReader(new FileReader("connection.txt"));
boolean readerStatus = fileReader.ready();
newLine = fileReader.readLine();
while (readerStatus)
{
StringTokenizer st = new StringTokenizer(newLine, ",");
while (st.hasMoreTokens())
{
dbDriver = st.nextToken();
dbUrl = st.nextToken();
dbName = st.nextToken();
dbUser = st.nextToken();
dbPassword = st.nextToken();
}
readerStatus = fileReader.ready();
System.out.println(dbDriver);
System.out.println(dbUrl);
System.out.println(dbName);
System.out.println(dbUser);
System.out.println(dbPassword);
}
Class.forName(dbDriver);
String url = dbUrl + dbName;
con = DriverManager.getConnection(url, dbUser, dbPassword);
}
catch (IOException ioex)
{
}
catch (SQLException sqlex)
{
}
catch (ClassNotFoundException cnfex)
{
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter printer = response.getWriter();
printer.println(con);
printer.println(dbDriver);
String title = "Result from custom query";
/*try
{
stmt = con.createStatement();
printer.println("<html><body><font color=black> test </font></body></html>");
rs = stmt.executeQuery("SELECT customerID" +
" FROM customer");
while (rs.next())
{
printer.println("<html> <head><title>" + title + "</title><br><br><table border=\"0\"> <tr><td>"
+ rs.getString(1));
}
}
catch (SQLException sqlx)
{
printer.println("SQL Exception");
sqlx.printStackTrace();
}*/
}
public void destroy()
{
try
{
rs.close();
stmt.close();
con.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
[/nobr]
# 19
I may sound selfish and arrogant, but why don't you try to use the line of code I posted before?
I know it's long, but you can copy and paste it ;-)
BufferedReader fileRead = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/connection.txt")));
This assumes connection.txt is on the WEB-INF/classes dir of your webapp
# 20
selfish and arrogant not at all. I did try using it and I had the same result. I must have forgot to post it.
init() just inst working, i am going to take the advice given and connect in doPost and kill the connection in doPost(). As I have had it up to here with init().
I will also employ your idea. I will get back to you
and thanks a tone!
# 21
[nobr]Hello Again,
I have made some changes to the servlet, mainly: getting rid of init() and destroy()
My connection is done in another method, and called from doPost()
when i compiled javac told me i had to catch or throw a Class not found exception, IOException andSQLExcepion and i did.
The Class not found exception fires when i run the code
code:
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CustomQuery extends HttpServlet
{
Connection con;
Statement stmt;
ResultSet rs;
BufferedReader fileRead;
PrintWriter printer;
String dbDriver = "";
String dbUrl = "";
String dbName = "";
String dbUser = "";
String dbPassword = "";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
try
{
printer = response.getWriter();
readFile();
connect();
query(request, response);
rs.close();
stmt.close();
con.close();
}
catch (SQLException sqlx)
{
printer.println("\n SQLException caught \n");
while (sqlx != null)
{
printer.println("Message:"
+ sqlx.getMessage());
printer.println("SQLState: "
+ sqlx.getSQLState());
printer.println("ErrorCode: "
+ sqlx.getErrorCode());
sqlx = sqlx.getNextException();
printer.println("");
}
}
catch (ClassNotFoundException cnfx)
{
printer.println("cnfx " + cnfx.getMessage());
}
catch (IOException ioex)
{
printer.println("ioex " + ioex.getMessage());
}
}
public void connect() throws SQLException, ClassNotFoundException
{
Class.forName(dbDriver);
String url = dbUrl + dbName;
con = DriverManager.getConnection(url, dbUser, dbPassword);
}
public void readFile() throws IOException
{
//fileRead = new BufferedReader(new FileReader("C://java/invoice/connection.txt"));
fileRead = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/connection.txt")));
boolean readerStatus = fileRead.ready();
String newLine = fileRead.readLine();
while (readerStatus)
{
StringTokenizer st = new StringTokenizer(newLine, ",");
while (st.hasMoreTokens())
{
dbDriver = st.nextToken();
dbUrl = st.nextToken();
dbName = st.nextToken();
dbUser = st.nextToken();
dbPassword = st.nextToken();
}
readerStatus = fileRead.ready();
}
}
public void query(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException
{
response.setContentType("text/html");
String title = "Result from custom query";
stmt = con.createStatement();
printer = response.getWriter();
printer.println("<html><body><font color=black> test </font></body></html>");
rs = stmt.executeQuery("SELECT customerID" + " FROM customer");
while (rs.next())
{
printer.println("<html> <head><title>" + title + "</title><br><br><table border=\"0\"> <tr><td>" + rs.getString(1));
}
}
}
[/nobr]
# 22
Class.forName(dbDriver); throws ClassNot Found error.Could mean a couple things, 1: The value of dbDriver is no a valid name of a JDBC driver.2: The JDBC driver class file is not in the class path of the web application.
# 23
*mental note: read through ALL the code before making a stupid remark...*Message was edited by: benubach
# 24
Any ideas anyone ?
I dont have the location for the diver in my classpath (the documentation for the MySql connector J said you could simply put the mysql-connector-java-3.0.17-ga-bin.jar file in the C:\Program Files\Java\jre1.6.0\lib\ext directory)
This code works when it was a console app, doesnt work as a servlet.
A professor of mine told me that there is a specific folder in Apache Tomcat 4.1 where my .txt file should be so the program can read from it, does anyone know where this is? and even when I hard coded the path to the file it didnt work.
Thanks
# 25
Put the MYSQL connector jar in $CATALINA_HOME/common/lib
It would be better to place the .txt file at the root of your source code/classes directory so you can read it with the method involving the getResourceAsStream method as the code requires no changes if you deploy on another machine (ie is portable :-p)
;-)
How is it going?
Message was edited by:
benubach
# 26
I got the first part about the location of the jdbc driver.I have 2 years college java experience and didnt understand much of what I read when I looked up getResourceAsStream() Can you explain how to use it and its benifits?
# 27
BufferedReader fileRead = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/connection.txt")));
That way of reading files is a very portable way to do it since it will lookup the file within the classpath, eliminating the need of hardcoding system specific file names/paths.
I also asked you to place the connection.txt file on the root of your source code so it can be found on the root of your classes directory (WEB-INF/classes/connection.txt) to load it as indicated above.
Hope i made myself clear. Anyway I'm around if i didn't ;-)
# 28
It Works!
Thank you very much. Thank all of you.
One more thing: do you have any websites that talk about the benefits of
BufferedReader fileRead = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/connection.txt")));
as opposed to
BufferedReader fileRead = new BufferedReader(new FileReader("connection.txt"));
again, thank you
# 29
You're welcome :-)
About the info sites you ask for, to be honest I just learnt that way of reading files. Don't remember the site, but I do know I was looking for a way to load .properties files with relative paths. Google for it and i'm sure you'll find a lot of useful info about it. Good Luck!