Solved

about java.lang.NullPointerException in struts connectionpoll.

Posted on 2004-08-23
14
401 Views
Last Modified: 2010-04-01
hi,experts,this is my config,why the nullpointer is created?

struts-config.xml:

    <!-- ========== Data Source Configuration =============================== -->
    <data-source class="com.microsoft.jdbc.sqlserver.SQLServerDriver" key="sqlPool">
      <set-property value="true" property="autoCommit" />
      <set-property value="com.microsoft.jdbc.sqlserver.SQLServerDriver" property="driverClass" />
      <set-property value="20" property="maxCount" />
      <set-property value="6" property="minCount" />
      <set-property value="btn" property="password" />
      <set-property value="sa" property="user" />
      <set-property value="jdbc:microsoft:sqlserver://btns:1433;DatabaseName=CommunityMedical" property="url" />
    </data-source>


---StrutsPollConnection:

package com.beltino.util;

import org.apache.struts.action.*;
import org.apache.struts.*;
import javax.sql.*;
import java.sql.*;
/**
 * @author aus
 */
public class StrutsPollConnection extends Action {
      private DataSource ds = null;
      private Connection conn = null;
      private Statement stmt;
      private Statement stmt2;
      private Statement stmt3;
      private Statement stmt4;
      private Statement stmt5;
      private Statement stmt6;

      public StrutsPollConnection() {
            try {
                  ds = (DataSource) servlet.getServletContext().getAttribute(Globals.DATA_SOURCE_KEY);
                  conn = ds.getConnection();
                  stmt = conn.createStatement();
                  stmt2 = conn.createStatement();
                  stmt3 = conn.createStatement();
                  stmt4 = conn.createStatement();
                  stmt5 = conn.createStatement();
                  stmt6 = conn.createStatement();
            } catch (Exception e) {
          e.printStackTrace();
            }
      }

      

      public ResultSet executeQuery(String sql) {
            try {
                  ResultSet rs = stmt.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }



      public ResultSet executeQuery2(String sql) {
            try {
                  ResultSet rs = stmt2.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }


      public ResultSet executeQuery3(String sql) {
            try {
                  ResultSet rs = stmt3.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }


      public ResultSet executeQuery4(String sql) {
            try {
                  ResultSet rs = stmt4.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }


      public ResultSet executeQuery5(String sql) {
            try {
                  ResultSet rs = stmt5.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }

      public ResultSet executeQuery6(String sql) {
            try {
                  ResultSet rs = stmt6.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }

      
      public boolean execute(String sql) {
            try {
                  stmt.execute(sql);
                  return true;
            } catch (Exception e) {
                  e.printStackTrace();
                  return false;
            }
      }

      
      public boolean executeUpdate(String sql) {
            try {
                  stmt.executeUpdate(sql);
                  return true;
            } catch (Exception e) {
                  e.printStackTrace();
                  return false;
            }
      }

      
      public PreparedStatement getPreparedStmt(String sql) {
            PreparedStatement prepStmt = null;
            try {
                  prepStmt = conn.prepareStatement(sql);
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return prepStmt;
      }

   //close
      public void close() {
            if (conn != null) {
                  try {
                        conn.close();
                        System.out.println("222222222222");
                        conn = null;
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
      
}


--UserBean

/* &#25551;&#36848;:
 * &#21019;&#24314;&#26085;&#26399; 2004-8-17
 * &#20316;&#32773;:jbas@163.com
 */
package com.beltino.communitymedical.system;

import com.beltino.util.*;
/**
 * @author aus
 */
public class UserBean {
      StrutsPollConnection dbConn=new StrutsPollConnection();
      boolean retSuccess=false;
      public boolean isLogin(User user) {
        String sql="";
            sql ="select * from TAccount where Account='" + user.getUserId() + "' and sPassWord='" + user.getPassword() + "'";
            try {
                  java.sql.ResultSet rs = dbConn.executeQuery(sql);
                  if (rs.next()) {
                        retSuccess=true;
                  } else {
                        retSuccess=false;
                  }
            } catch (Exception e) {
                  System.out.println("err");
                  e.printStackTrace();
                  retSuccess=false;
            }finally{
              dbConn.close();
              System.out.println("11111111");
          return retSuccess;
            }
      }
}
0
Comment
Question by:hgbdelphi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
14 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 11868389
What line is it that throws the exception?

Can you post your stack trace?

You never close the statements!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11868396
If the call fails, you return null, but in this code:

               java.sql.ResultSet rs = dbConn.executeQuery(sql);
               if (rs.next()) {

you never check if rs is null!
0
 

Author Comment

by:hgbdelphi
ID: 11868419
hi,TimYates,
this is the error:


java.lang.NullPointerException
        at com.beltino.util.StrutsPollConnection.<init>(StrutsPollConnection.jav
a:26)
        at com.beltino.communitymedical.system.UserBean.<init>(UserBean.java:12)

        at com.beltino.communitymedical.system.UserAction.execute(UserAction.jav
a:57)
        at org.apache.struts.action.RequestProcessor.processActionPerform(Reques
tProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.ja
va:274)
        at com.beltino.util.EncodingActionServlet.process(EncodingActionServlet.
java:27)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)

        at javax.servlet.http.HttpServlet.service(HttpServlet.java:165)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)
        at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterC
hain.java:113)
        at com.caucho.server.cache.CacheFilterChain.doFilter(CacheFilterChain.ja
va:190)
        at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain
.java:177)
        at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocatio
n.java:221)
        at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:263
)
        at com.caucho.server.port.TcpConnection.run(TcpConnection.java:331)
        at com.caucho.util.ThreadPool.runTasks(ThreadPool.java:464)
        at com.caucho.util.ThreadPool.run(ThreadPool.java:408)
        at java.lang.Thread.run(Thread.java:534)
java.lang.NullPointerException
        at com.beltino.util.StrutsPollConnection.executeQuery(StrutsPollConnecti
on.java:43)
        at com.beltino.communitymedical.system.UserBean.isLogin(UserBean.java:18
)
        at com.beltino.communitymedical.system.UserAction.execute(UserAction.jav
a:59)
        at org.apache.struts.action.RequestProcessor.processActionPerform(Reques
tProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.ja
va:274)
        at com.beltino.util.EncodingActionServlet.process(EncodingActionServlet.
java:27)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)

        at javax.servlet.http.HttpServlet.service(HttpServlet.java:165)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)
        at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterC
hain.java:113)
        at com.caucho.server.cache.CacheFilterChain.doFilter(CacheFilterChain.ja
va:190)
        at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain
.java:177)
        at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocatio
n.java:221)
        at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:263
)
        at com.caucho.server.port.TcpConnection.run(TcpConnection.java:331)
        at com.caucho.util.ThreadPool.runTasks(ThreadPool.java:464)
        at com.caucho.util.ThreadPool.run(ThreadPool.java:408)
        at java.lang.Thread.run(Thread.java:534)
err
java.lang.NullPointerException
        at com.beltino.communitymedical.system.UserBean.isLogin(UserBean.java:19
)
        at com.beltino.communitymedical.system.UserAction.execute(UserAction.jav
a:59)
        at org.apache.struts.action.RequestProcessor.processActionPerform(Reques
tProcessor.java:484)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.ja
va:274)
        at com.beltino.util.EncodingActionServlet.process(EncodingActionServlet.
java:27)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)

        at javax.servlet.http.HttpServlet.service(HttpServlet.java:165)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)
        at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterC
hain.java:113)
        at com.caucho.server.cache.CacheFilterChain.doFilter(CacheFilterChain.ja
va:190)
        at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain
.java:177)
        at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocatio
n.java:221)
        at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:263
)
        at com.caucho.server.port.TcpConnection.run(TcpConnection.java:331)
        at com.caucho.util.ThreadPool.runTasks(ThreadPool.java:464)
        at com.caucho.util.ThreadPool.run(ThreadPool.java:408)
        at java.lang.Thread.run(Thread.java:534)
11111111
[16:41:11.093] Closing dangling connections.  All connections must have a close(
) in a finally block.
[16:41:11.093] java.lang.IllegalStateException: Connection UserConnectionAdapter
[] was not closed. Connections must have a close() in a finally block.
[16:41:11.093]  at com.caucho.jca.UserTransactionImpl.abortTransaction(UserTrans
actionImpl.java:407)
[16:41:11.093]  at com.caucho.jca.UserTransactionProxy.abortTransaction(UserTran
sactionProxy.java:171)
[16:41:11.093]  at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFil
terChain.java:197)
[16:41:11.093]  at com.caucho.server.dispatch.ServletInvocation.service(ServletI
nvocation.java:221)
[16:41:11.093]  at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.
java:263)
[16:41:11.093]  at com.caucho.server.port.TcpConnection.run(TcpConnection.java:3
31)
[16:41:11.093]  at com.caucho.util.ThreadPool.runTasks(ThreadPool.java:464)
[16:41:11.093]  at com.caucho.util.ThreadPool.run(ThreadPool.java:408)
[16:41:11.093]  at java.lang.Thread.run(Thread.java:534)
closing server
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11868462
              conn = ds.getConnection();
               stmt = conn.createStatement();
               stmt2 = conn.createStatement();
               stmt3 = conn.createStatement();
               stmt4 = conn.createStatement();
               stmt5 = conn.createStatement();
               stmt6 = conn.createStatement();

It seems you use just one connection to create many more statement. I think it should not work. You should use one connection per statement.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11868481
1) You will probably have problems opening that many statements at once on a connection...  I think the Oracle driver supports this, but as you are using the SQLServer one, I don't think it does
2) You could do with checking that ds is not null in the constructor.
3) You could do with checking that conn is not null in the constructor
4) You never close any statements.  Relying on conn.close() to close them all is a Bad Idea

If you want to do something like this, I would create the statement when it is needed, get a result set, read it fully into your own wrapper class (extends ArrayList?), then close resultset and the statement

0
 

Author Comment

by:hgbdelphi
ID: 11868561
hi,TimYates ,sompol_kiatkamolchai

 now i have create one statement,but the error is either exist

i think ds is null
1&#12289;  ds = (DataSource) servlet.getServletContext().getAttribute(Globals.DATA_SOURCE_KEY);
2&#12289; //ds = (DataSource) servlet.getServletContext().getAttribute("sqlPool");
1 or 2 i should use??
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11868583
I'd try 2
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11868585
If think you have to add code to check whether ds is null or not

ds = ....
if ( ds == null ) {
  System.out.println("debug sth");
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11868604
HANG ON!

That won't work, you are not using the struts datasource definition correctly...

Look here:

http://struts.apache.org/faqs/database.html
0
 

Author Comment

by:hgbdelphi
ID: 11868707
hi,TimYates and sompol_kiatkamolchai ,
i see the url, and download the Commons DBCP,and copy it in my web-inf/lib
but the error is exists,
now i now this i have not get the datasource,because this statement will create error:
   ds = (DataSource) servlet.getServletContext().getAttribute("sqlPool");

the error is:
java.lang.NullPointerException
        at com.beltino.util.StrutsPollConnection.<init>(StrutsPollConnection.jav
a:28)

i change the struts-config.xml ,like this ,but the error is exists!

<data-source type="org.apache.commons.dbcp.BasicDataSource">
    <set-property
      property="driverClassName"
      value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
    <set-property
      property="url"
      value="jdbc:microsoft:sqlserver://btns:1433;DatabaseName=CommunityMedical" />
    <set-property
      property="username"
      value="sa" />
    <set-property
      property="password"
      value="btn" />
    <set-property
      property="maxActive"
      value="10" />
    <set-property
      property="maxWait"
      value="5000" />
    <set-property
      property="defaultAutoCommit"
      value="false" />
    <set-property
      property="defaultReadOnly"
      value="false" />
</data-source>
0
 
LVL 35

Accepted Solution

by:
TimYates earned 60 total points
ID: 11868778
You cannot just do getAttribute, as the datasource is defined in your struts-config...

If this is inside an Action, you need to do getDatasource( request )

If not (looking at the source of Action.class) gives us the following (when you fill in the blanks, and get rid of the request object by filling in code from the classes it calls:

        ServletContext context = getServlet().getServletContext();

        ModuleConfig moduleConfig = (ModuleConfig)context.getAttribute( Globals.MODULE_KEY );


        // Return the requested data source instance

        return ((DataSource) context.getAttribute( Globals.DATA_SOURCE_KEY + moduleConfig.getPrefix() ) ) ;

0
 
LVL 11

Assisted Solution

by:sompol_kiatkamolchai
sompol_kiatkamolchai earned 40 total points
ID: 11868848
Here is an example.

public ActionForward
       execute(ActionMapping mapping,
               ActionForm form,
               HttpServletRequest request,
               HttpServletResponse response) throws Exception
{
 javax.sql.DataSource dataSource;
 java.sql.Connection myConnection;
 try {
  dataSource = getDataSource(request);
  myConnection = dataSource.getConnection();
  // do what you wish with myConnection
 } catch (SQLException sqle) {
    getServlet().log("Connection.process", sqle);
 } finally {
    //enclose this in a finally block to make
    //sure the connection is closed
    try {
       myConnection.close();
    } catch (SQLException e) {
       getServlet().log("Connection.close", e);
    }
   }
}
0
 

Author Comment

by:hgbdelphi
ID: 11878221
hi,TimYates ,sompol_kiatkamolchai
  thanks for your help,now it can work fine.this is my code.

1,
struts-config.xml:

    <data-sources>
        <data-source>
            <set-property property="password" value="btn" />
            <set-property property="minCount" value="1" />
            <set-property property="maxCount" value="20" />
            <set-property property="user" value="sa" />
            <set-property property="driverClass" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
            <set-property property="description" value="StrutsDataSourceConfig" />
            <set-property property="url" value="jdbc:microsoft:sqlserver://btns:1433;DatabaseName=CommunityMedical" />
            <set-property property="readOnly" value="false" />
            <set-property property="autoCommit" value="false" />
            <set-property property="loginTimeout" value="5000" />
        </data-source>
    </data-sources>

2,

/*
 *  2004-8-23
 * author:jbas@163.com
 */
package com.beltino.util;

import javax.sql.*;
import java.sql.*;
import org.apache.struts.config.*;
import org.apache.struts.Globals;
import javax.servlet.*;
/**
 * @author aus
 */
public class StrutsPollConnection {
      private Connection conn = null;
      private Statement stmt;
      private ServletContext context = null;

      public StrutsPollConnection(ServletContext context) {
            try {
                  ModuleConfig moduleConfig =
                        (ModuleConfig) context.getAttribute(Globals.MODULE_KEY);
                  DataSource ds =
                        ((DataSource) context
                              .getAttribute(
                                    Globals.DATA_SOURCE_KEY + moduleConfig.getPrefix()));
                  this.conn = ds.getConnection();
                  stmt = conn.createStatement();

            } catch (Exception e) {
                  System.out.println("error");
            }
      }

      //
      public ResultSet executeQuery(String sql) {
            try {
                  ResultSet rs = stmt.executeQuery(sql);
                  return rs;
            } catch (Exception e) {
                  e.printStackTrace();
                  return null;
            }
      }

      //
      public boolean execute(String sql) {
            try {
                  stmt.execute(sql);
                  return true;
            } catch (Exception e) {
                  e.printStackTrace();
                  return false;
            }
      }

      //       
      public boolean executeUpdate(String sql) {
            try {
                  stmt.executeUpdate(sql);
                  return true;
            } catch (Exception e) {
                  e.printStackTrace();
                  return false;
            }
      }

      //
      public PreparedStatement getPreparedStmt(String sql) {
            PreparedStatement prepStmt = null;
            try {
                  prepStmt = conn.prepareStatement(sql);
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return prepStmt;
      }

      //close
      public void close() {
            if (conn != null) {
                  try {
                        conn.close();
                        conn = null;
                        try {
                              if (stmt != null) {
                                    stmt.close();
                                    stmt = null;
                              }
                        } catch (Exception e) {
                              e.printStackTrace();
                        }

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

}

3,
// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (Bad file descriptor))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.beltino.communitymedical.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beltino.communitymedical.util.*;
import com.beltino.communitymedical.pub.*;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
 * UserAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net
 * created on 08-17-2004
 *
 * XDoclet definition:
 * @struts:action validate="true"
 */
public class UserAction extends Action {

      // --------------------------------------------------------- Instance Variables

      // --------------------------------------------------------- Methods

      /**
       * Method execute
       * @param ActionMapping mapping
       * @param ActionForm form
       * @param HttpServletRequest request
       * @param HttpServletResponse response
       * @return ActionForward
       * @throws Exception
       */
      public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
            UserForm f = (UserForm) form;
            boolean isLogin = false;
            UserBean userBean = null;

            TReadPropFile propFile = new TReadPropFile();

            SystemUserInfo systemUserInfo = new SystemUserInfo();

            SystemInfo systemInfo = new SystemInfo();

            try {
                  userBean = new UserBean(getServlet().getServletContext());

                  isLogin = userBean.isLogin(f.getUser());

            } catch (Exception e) {
                  e.printStackTrace();
            }
            if (isLogin == true) {
           System.out.println("logined");
            } else {
           System.out.println("not logined");

            }
            return null;
      }
}

4,

package com.beltino.communitymedical.system;

import com.beltino.util.*;
import javax.servlet.*;
/**
 * @author aus
 */
public class UserBean {
      boolean retSuccess=false;
      StrutsPollConnection dbConn=null;
            
      public UserBean(ServletContext context){
            dbConn=new StrutsPollConnection(context);
      }

   

      public boolean isLogin(User user) {
        String sql="";
            sql ="select * from TAccount where Account='" + user.getUserId() + "' and sPassWord='" + user.getPassword() + "'";
            try {
                  java.sql.ResultSet rs = dbConn.executeQuery(sql);
                  if (rs.next()) {
                        retSuccess=true;
                  } else {
                        retSuccess=false;
                  }
            } catch (Exception e) {
                  retSuccess=false;
            }finally{
              dbConn.close();
          return retSuccess;
            }
      }
      
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11878525
Yay! :-)

Glad you got it going ok!

Good luck!


Tim
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There is a lot to be said for protecting yourself and your accounts with 2 factor authentication.  I found to my own chagrin, that there is a big downside as well.
Let’s face it: one of the reasons your organization chose a SaaS solution (whether Microsoft Dynamics 365, Netsuite or SAP) is that it is subscription-based. The upkeep is done. Or so you think.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question