1
votes

I am working on a project that is accessing PostgreSQL with a jdbc driver and process this data through a middleware and finally displays/updates via jsp pages. Using Eclipse I created a Dynamic Web Project. Then I have written code for all back-end and middleware operations. I can access database from static context (I mean main method of java sources). I can also use my java resources (e.g displaying) from jsp if I don't call any methods that are accessing database. But when I try to access database, it doesn't work and gives me a null pointer exception.

<jsp:useBean id="user" class="dbActionManagement.UserData" scope="session"/> 
<jsp:setProperty name="user" property="*"/> 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>next page</title>
</head>
<body>

You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>

</body>
</html>

This gives me:

SEVERE: Servlet.service() for servlet [jsp] in context with path [/GNYSweb] threw exception [java.lang.NullPointerException] with root cause java.lang.NullPointerException at dbActionManagement.OfficerManager.getTotalPoint(OfficerManager.java:494) at dbActionManagement.UserData.getUsername(UserData.java:28) at org.apache.jsp.NextPage_jsp._jspService(NextPage_jsp.java:80) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)

Also java class that I am using for this is UserData and method getUserName()

public String getUsername() { 
        int a = new OfficerManager().getTotalPoint("a");
        return new Integer(a).toString(); 
}

OfficerManager has a default constructor and getTotalPoint is

public int getTotalPoint(String officerId){
    int point = 0;
    ResultSet results = null;
    try {
        if(DBConnection.db.isClosed()){ // problem is caused by this line 
            DBConnection.connect(); 
        }
        Statement sql = DBConnection.db.createStatement();
                String sqlText = "select point from officers ";

            sqlText += " where sicilno = '" + officerId + "'";
        results = sql.executeQuery(sqlText);

    } catch (SQLException e) {
        e.printStackTrace();

    }
    if(results != null)
        try {
            while(results.next()){
                point = (int) results.getDouble("point");

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    return point;
}

I have added postgreSQL jdbc driver to my build path. Also I included same jdbc driver in the lib folder of Tomcat. Also I am using an instance of Tomcat v7.0 at localhost and the location of this is [workspace metadata]

2
NPE means something is null. For example db. Make sure it's not null - Bozho
Is DBConnection a class with static methods like db? Try moving the connection initialization out of there. - Dmitry Alexandrov

2 Answers

1
votes

I understand the problem, it is basically I was trying to reach Connection object that is null. I use static objects for accessing database, I forgot to initialize them before using. There are several solutions for this, the most basic one is to write another method in UserData class called startConnection()

public void startConnection(){
    new DBConnection("myDBName", "myUserName", "myPassword");
}

and call this method from jsp pages

...
<body>
<% user.startConnection(); %>
Name: <%= user.getUsername() %><BR>
</body>
...

That way I can initialize my DBConnection class instances properly before using them. Thanks for your help.

0
votes

Avoid checking if the db is closed before connection is created, comment out:

 //if(DBConnection.db.isClosed()){ // problem is caused by this line 
        DBConnection.connect(); 
  //  }

And then close the connection after using it and when an exception occurs. Your exception block should be changed to;

catch (SQLException e) 
{
 e.printStackTrace();
 if((DBConnection !=null) && DBConnection.db !=null && !DBConnection.db.isClosed())
    {
      BConnection.db.close(); 
    }
}

And also close it in the try block straight after usage.

As rule of thumb - alway check if the connection is not null before attempt closing it. try doing something like this:

if((DBConnection !=null) && DBConnection.db !=null && DBConnection.db.isClosed())
{
  DBConnection.connect(); 
}