Cannot create JDBC driver of class...

Discussions

Web tier: servlets, JSP, Web frameworks: Cannot create JDBC driver of class...

  1. Cannot create JDBC driver of class... (75 messages)

    I know that this problem has been posted numerous times but none of the solutions has worked for me. I am using Tomcat 4.1.30 and am still getting an error that says

     org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null', cause:
    java.sql.SQLException: No suitable driver

    Here is my server.xml :

    <context path="/StrutsTest" docBase="StrutsTest" debug="1" reloadable="true">
    <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_StrutsTest_log." suffix=".txt" timestamp="true"/>
    <Resource name="jdbc/FieldProjDB" auth="Container" type="javax.sql.DataSource" />
    <ResourceParams name="jdbc/FieldProjDB">
    <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <parameter>
    <name>user</name>
    <value>lab</value>
    </parameter>
    <parameter>
    <name>password</name>
    <value>lab</value>
    </parameter>
    <parameter>
    <name>driverClassName</name>
    <value>net.sourceforge.jtds.jdbc.Driver</value>
    </parameter>
    <parameter>
    <name>url</name>
    <value>jdbc:jtds:sqlserver://192.xxx.xx.xx:1433/LabSeekDev;User=lab;Password=lab</value>
    </parameter>
    </ResourceParams>
    </context>

    Here is my web.xml :

      <resource-ref>
        <res-ref-name>
            jdbc/FieldProjDB
        </res-ref-name>
        <res-type>
            javax.sql.DataSource
        </res-type>
        <res-auth>
            Container
        </res-auth>
      </resource-ref>

    Here is my code snippet :

          Connection conn = null;
          Context initCtx = new InitialContext();
          DataSource ds =
                (DataSource)initCtx.lookup("java:comp/env/jdbc/FieldProjDB");
          if (ds != null) {
            conn = ds.getConnection();
    }

    I have been trying to fix this problem for a week now and its getting very frustrating. Any help would be appreciated.

    Threaded Messages (75)

  2. It looks like you need to put the jar file containing the driver in your WEB-INF/lib directory.
  3. I have put the JDBC jar file in %Tomcat Home%/common/lib directory, as recommended by Tomcat.
  4. After trying out various things with the server.xml file, I modified the 'docBase' in context like this :
    <Context path="/StrutsTest" docBase="StrutsTest.war" debug="1" reloadable="true">
    So instead of docBase="StrutsTest", I put docBase="StrutsTest.war". With this configuration, I can get my data source to work! But the only thing is that the war file is not unpacked under webapps folder but directly under %TOMCAT_HOME%/work/Standalone/localhost. I know that all deployed apps get listed here but why does it not put it in webapps folder as well?
  5. Cannot create JDBC driver of class...[ Go to top ]

    for tomcat-5.0.18
    i use ROOT in tomcat as by web app i put the following entry in E:\jakarta-tomcat-5.0.18\conf\Catalina\localhost\ROOT.xml file
    for tomcat-4.1.18
    i use ROOT in tomcat as my webapp i put the following entry in E:\qrules\tomcat\jakarta-tomcat-4.1.18\conf\server.xml

    <ResourceLink name="jdbc/quickstart" type="javax.sql.DataSource" global="jdbc/quickstart"/>

    -:)it started working
  6. I haven't tested to confirm, but I would try specifying your docBase as StrutsTest instead of StrutsTest.war. By specifying the war as a docBase, you're probably telling Tomcat to run the webapp from the war file.
  7. Very annoying...[ Go to top ]

    Hmm,
     Having been hit by this today, and judging from the volume of postings I've seen on this topic, the Jakarta boys should think of beefing up their documentation and make to clarify a few things:

    1) Why do I need to put a (renamed) copy of my web application's META-INF/context.xml file into Tomcat's conf/Catalina/ folder before starting up my server? (I had to rename it to the same name as my context e.g. test-app.xml). Without this, it consistently failed to open a connection.

    1) The actual error message returned in the Exception is a bit misleading - the message indicates that the problem appears to be because the Class and URL are null. However, the problem is really that Tomcat can't read the context configuration file (perhaps an web-app startup error message should if no context.xml or context entry exists in the server.xml.

    2) The JDBC driver classes *must* go into common/lib. Putting them in the WEB-INF/lib isn't good enough, nor is putting them in any other shared location (e.g. shared/lib or server/lib). This is because Tomcat uses Jakarta Commons DBCP libraries to instanciate the JDBC Driver class and the Tomcat Classloader hierarchy won't find the driver file unless it's loaded by the same classloader.

    John.
  8. I was having the same problem . But the only difference is i'm using db2udb on windows. I spent nearly 10 hours to figure this out . It took so much time because i was reading lots of junk on the net and confusing. Finally i stick to the tomcat documentation.

    The solution is very simple.
    1) Remove the context element from your server.xml
    2) create separate xml file with context element and copy the below code and name the file as contextpath ( in your case it is StrutsTest).

    <context path="/StrutsTest" docBase="StrutsTest" debug="1" reloadable="true">
    <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_StrutsTest_log." suffix=".txt" timestamp="true"/>
    <Resource name="jdbc/FieldProjDB" auth="Container" type="javax.sql.DataSource" />
    <ResourceParams name="jdbc/FieldProjDB">
    <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <parameter>
    <name>user</name>
    <value>lab</value>
    </parameter>
    <parameter>
    <name>password</name>
    <value>lab</value>
    </parameter>
    <parameter>
    <name>driverClassName</name>
    <value>net.sourceforge.jtds.jdbc.Driver</value>
    </parameter>
    <parameter>
    <name>url</name>
    <value>jdbc:jtds:sqlserver://192.xxx.xx.xx:1433/LabSeekDev;User=lab;Password=lab</value>
    </parameter>
    </ResourceParams>
    </context>
    3)modify the docbase attribute of context element in the above file .
     docBase = absolute pathname to a web application .(according to tomcat documentation)
    for example: docBase = c:\yourapp\web ( note web is a contextpath)
    4)copy the file to $CATALINA_HOME/conf/[engine_name]/[host_name] directory .
    5)start the tomcat server.
    6)thats it.
    7)your feedback is appreciated.
  9. I was having the same problem.

    I found it strange that in Tomcat How-tos they don't mention the <Context> element. After reading your post i just added the
    <context path="/myApp" docBase="myApp" debug="1" reloadable="true">
    and it worked perfectly.

    Thanks!!

    Rgds,

    Marco
  10. Thanks Marco,
    I had the same problem, you mentioned and with your help I fixed it.

    By the it would be interesting to me, why tomcat behaves like this?
    Any ideas or explanations?

    Bye Johannes
  11. thank you very much venkat in helping to solve the problem.
  12. My problem is not rectified[ Go to top ]

    I am trying to configure Tomcat5.0 with mysql. I followed the steps according to your posting, but i am getting the same error. contextpath.xml <!-- Cofiguring the connection pooling with tomcat and mysql --> factory org.apache.commons.dbcp.BasicDataSourceFactory <!-- Maximum number of DB Connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your DB Connections. Set to 0 for no limit --> maxActive 100 <!-- Maximum number of idle DB Connections to retain in Pool Set to 0 for no limit --> maxIdle 10 <!-- Maxmimum time to wait for DB Connection to become available in milliseconds, in this example 10seconds. An exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely --> maxWait 10000 <!-- Mysql Db username and password for DB Connections --> username root password root <!-- Class name for com.mysql Jdbc Driver --> driverClassName com.mysql.jdbc.Driver <!-- The JDBC Connection for connecting to your mysql db . The autoReconnect=true argument to the url make sure that the mm.mysql JDBC Driver will automatically reconnect if mysqld closed the connection. Mysqld by default close idle connections after 8 hours --> url jdbc:mysql://localhost:3306/test removeAbandoned true removeAbandonedTimeout 60 <!-- End of Connection pooling configuration --> Thanks in advance Ashok kumar
  13. Re: My problem is not rectified[ Go to top ]

    thanks for all these posts. The problem is that for each release of tomcat there is a different way of doing it. I did it for Tomcat 4.1,5.0,5.5.23. All the time for MSSQLSERVER2000 You Follow these steps to get your DBCP working with Tomcat 5.5.23. There is no need to change the web.xml. 1) Install fresh Tomcat 5.5.23 from apache’s website. 2) Install the compatibility package for JDK 1.4(in case you don’t have J2SE 5 installed) 3) Put all the required commons(dbcp,collections,pool) and driver(mssql,msutil,msbase)jar files in Tomcat_home\common\lib 4) Put a xml file called yourContext.xml(whatever is the context for your webapplication) at tomcat_home\conf\Catalina\localhost Make entries to the yourContext.xml in following manner: Example:--- 5) add following entries to your server.xml at tomcat_home\conf example----- one context entry :---- One global naming resources entry:---- 6)To look up the datasource and get the connection add the following code to your Java Class:- Connection con=null; Context ctx = null; //For DataSources DataSource ds=null; //For DataSources ctx = new InitialContext(); //For DataSources Context envContext = (Context)ctx.lookup("java:/comp/env"); ds = (DataSource)envContext.lookup("DataSourceName"); con = ds.getConnection(); //For DataSources 7)start the server and test the connection.
  14. Hi folks, Sorry for length of post, but I've got lots of questions... I've been reading Core JSF 2nd ed. It indirectly mentions using commons-dbcp, so you can do things like poolPreparedStatements and consequently prevent things like SQL injection. I've adapted example to MySQL from Postgres below. They've used a xml node which I think is dubious '' which they say goes in the '' node of the server.xml file. (See questions 3 & 4 later about best place to host this) factory org.apache.commons.dbcp.BasicDataSourceFactory driverClassName com.mysql.jdbc.Driver url jdbc:mysql://127.0.0.1:3306/jgf username xxx password xxx maxActive 20 maxIdle 10 poolPreparedStatements true Now I read earlier in this thread on Serverside when one guy used commons-dbcp & commons-pool. I didn't have latter yesterday when I tried, so I thought I'd check out dependencies for commons-dbcp-1.2.2 over at: http://www.mvnrepository.com/artifact/commons-dbcp/commons-dbcp/1.2.2 They I happened to notice by accident there is a tomcat-dbcp.jar already in the tomcat lib. 1) So I guess my first question is can you use this instead with Tomcat 6? This is what the Tomcat 6 docs says: (See section 4. Configure Tomcat's Resource Factory) http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html It makes no reference to prepared statements - just the glib statement "For more details, please refer to the commons-dbcp documentation". Documentation for this appears to be very thin on the ground. Maybe I've overlooked something.. I notice the verbose nodes used in Core JSF first example hve been dropped in favour of attributes and there is no longer a distinction between 'Resource' and 'ResourceParams' nodes. Everything is rolled into one. ... ... 2) Can I add a poolPreparedStatement attribute? Also http://tomcat.apache.org/tomcat-6.0-doc/config/context.html has section about where context can appear. 3) Am I right in assuming you don't need to place in server.xml. You can put it in context.xml instead? 4) Why use server.xml over context.xml or vice-versa? Quote: Context elements may be explicitly defined: - in the $CATALINA_HOME/conf/context.xml file: the Context element information will be loaded by all webapps - in the $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host - in individual files (with a ".xml" extension) in the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml extension) will be used as the context path. Multi-level context paths may be defined using #, e.g. context#path.xml. The default web application may be defined by using a file called ROOT.xml. - if the previous file was not found for this application, in an individual file at /META-INF/context.xml inside the application files - inside a Host element in the main conf/server.xml BTW: I've been able to successfully set up Connection pooling in Glassfish, by using MySQL's own connection pooling class. com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource 5) Is there a way to configure this instead within Tomcat including allowing PreparedStatements?
  15. DBCP footnote:[ Go to top ]

    http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html Mentions DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components: Jakarta-Commons DBCP Jakarta-Commons Collections Jakarta-Commons Pool Maven doesn't say anything about collections... http://www.mvnrepository.com/artifact/commons-dbcp/commons-dbcp/1.2.2 Collections seem to be specific to earlier versions of dbcp. I think the folks at Tomcat should update their documentation accordingly..
  16. Answer about DHCP jars..[ Go to top ]

    Then I happened to notice by accident there is a tomcat-dbcp.jar already in the tomcat lib.
    1) So I guess my first question is can you use this instead with Tomcat 6? blockquote> Just found answer to this question.. http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components: Jakarta-Commons DBCP Jakarta-Commons Collections Jakarta-Commons Pool These libraries are located in a single JAR at $CATALINA_HOME/lib/tomcat-dbcp.jar. However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.
  17. 3) Am I right in assuming you don't need to place in server.xml. You can put it in context.xml instead?

    4) Why use server.xml over context.xml or vice-versa?
    Found answer to 3 & 4 here: http://tomcat.apache.org/tomcat-6.0-doc/config/context.html Quote "For Tomcat 6, unlike Tomcat 4.x, it is NOT recommended to place elements directly in the server.xml file. This is because it makes modifing the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat."
  18. Apart from the syntatic changes of using verbose nodes versus attributes, the two main differences between Core JSF and Tomcat 6 documentation is: Inclusion of: factory="org.apache.commons.dbcp.BasicDataSourceFactory" poolPreparedStatements="true" I did manage to track down some DHCP documentation eventually but still unclear about factory attribute See: http://commons.apache.org/dbcp/configuration.html I've also noted earlier in this thread Burak Emir on January 06, 2005 said user & password sometimes don't work with MySQL, so you append to url as follows: url="jdbc:mysql://localhost:3306/nameOfDB?autoReconnect=true&user=hurrah&password=secret" Could this be down to attribute name of username versus user? Or is this a red-herring? Would still like to know about DefaultContext. Have also noted here: http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html Please note that although the above instructions place the JNDI declarations in a Context element, it is possible and sometimes desirable to place these declarations in the GlobalNamingResources section of the server configuration file. A resource placed in the GlobalNamingResources section will be shared among the Contexts of the server. So does this mean I should go back to server.xml? Or an GlobalNamingResources be placed in context.xml too? God this is confusing. Too many options!
  19. factory attribute...[ Go to top ]

    I mentioned factory attribute in regards to DBCP above. Is this factory attribute the same one defined in element of which I believe I am right in saying can only be in server.xml and would be same one I mentioned in initial post about Core JSF?
  20. Right I got there in the end. What a painful process though! Here goes. Many thanks to Bryan Dickey for his final post here: http://forum.java.sun.com/thread.jspa?threadID=624382&messageID=3553968 1) In Server.xml in Tomcat\conf place the following in node: 2) In context.xml add this within Context node:
  21. I forgot to mention, Tomcat repackagedBasicDataSourceFactory, so factory attribute had to be tweaked.
  22. Did you find solution[ Go to top ]

    This whole issue seems to be so tenuous.

    I have same nearly setup - tomcat 5.0.27, jtds 0.9 rc2, and sql 2000 and hiberate. my difference is i am in ROOt context - i was very hopeful reading about parsing out the ROOT.xml file into catalina/localhost/ from the web.xml, but that didnt do the trick.

    I get the same error.

    I have tried making sure there are no jar file conflicts (though that is a little unclear too - what is difference between server, common and shared (i have read some on tomcat site, but not conclusive).

    I know tomcat is looking at my config as when i make a typo in the ROOT.xml config, it throws an error, but it doesnt seem to find the driver/database during runtime.
  23. my problem resolved[ Go to top ]

    I was using the default dbcp apache connection pool which i don't think i had setup right, or if i did, it wasnt working. I installed and configured the c3p0 connection pool and it works like magic.
  24. Tomcat 5.5.4[ Go to top ]

    I am using Tomcat 5.5.4, Oracle 9i, classes12.jar, on windows xp and encountered this error. I was able to resolve it by putting my connection data inside the Resource element, instead of a ResourceParams element.

    This is my /META-INF/context.xml file from my war file (a cool feature of either 5.5 or 5.0 is that this is automatically copied over and renamed in the $CATALINA_HOME/conf/Catalina/localhost/ directory on deploy).
    -----------------------------------------------------
    <Context path="/KOS-MOS" docBase="KOS-MOS" debug="1" reloadable="true">
      <Resource name="jdbc/ncsuoracle" auth="Container"
        type="javax.sql.DataSource"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@orcl.csc.ncsu.edu:1521:ORCA" username="phil"
        password="passwd" maxActive="20" maxIdle="10" maxWait="-1" />
    </Context>
    -----------------------------------------------------
  25. Complete Solution[ Go to top ]

    Works for me with Tomcat 5.0:

    1. Put Datasource into server.xml
       ...
       <Resource name="jdbc/dsname" scope="Sharable" auth="Container" type="javax.sql.DataSource"/>
       <ResourceParams name="jdbc/dsname">
          <parameter>
       ...

    2. Put a reference to this Datasource into the application's context (in server.xml or better in /META-INF/context.xml:

       <Context ...
       <ResourceLink global="jdbc/dsname" name="jdbc/dsname" type="javax.sql.DataSource"/>
       ...
       </Context>
  26. What worked for me[ Go to top ]

    Thanks to all of you. By some estimates, you saved me about 9 hours time.

    Putting the driver in the common/lib/endorsed was sufficent for me (I was using Tomcat5.0.28), not to disagree with John O'Shea, above.

    It was also necessary to put the ResourceLink element in my application descriptor (as suggested by Bernd Weinand, above), which was at the following location: C:\ProgramFiles\ApacheGroup\Tomcat5.0.28\conf\Catalina\localhost\axis.xml

    Lastly, I didn't need to modify server.xml by hand, as the admin page (at http://localhost:8080/admin/) allowed me to add the DataSource quite nicely.

    Thanks again. God Bless You, and Merry Christmas!
  27. Complete Solution[ Go to top ]

    I used Bernd's solution and it worked for me.
    I'm also with Tomcat 5.0(.28), added nothing to the web.xml
    The difference is that I put the context file myapp.xml in Tomcat/conf/Catalina/localhost/ instead of naming it context.xml and putting it in /META-INF/ because it didn't work for me.

    I'd like to have it worked the other way. If someone have the solution ...

    As well, can we (easily ;-P) configure the datasource in the web.xml ?, so that we don't have to change the server configuration in the future, only the webapp itself.

    Thanks
    Manu
  28. Complete Solution[ Go to top ]

    Thanks Manu . Your suggestion is worked for my case.
  29. Tomcat 5.5.4[ Go to top ]

    Thanks Philihp! I put almost 20 hours into trying to get my Tomcat 5.5.4 to connect into a SQL Server 2000 database. I wasted a lot of time trying to get the Resource Params to work and couln't get anywhere. As soon as I switched over to your way using <Resource> INSTEAD OF <ResourceParams> it worked fine.

    One more thing to watch out for in this process - a lot of the previous postings are using "org.apache.commons.dbcp.BasicDataSourceFactory"
    and Tomcat 5.5.4 uses "org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"

    Here is my Context xml file for my Web app going against MS SQL Server:

    <Context path="/workflow" docBase="C:/development/environment/tomcat/jakarta-tomcat-5.5.4/webapps/workflow" debug="1" reloadable="true">
    <Resource name="jdbc/DefaultDS" auth="Container" type="javax.sql.DataSource"
    factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
    user="apworkflow"
    password="workflow"
    driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
    url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=apworkflow;User=apworkflow;Password=workflow;selectMethod=cursor"
    maxWait="-1" removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"/>
    </Context>
  30. Tomcat 5.5.4 addendum[ Go to top ]

    Thanks also to you Marty, you summed it up very neatly.

    Here's my 2p worth: I am using the mySQL Connector-J and user password attributes seem to be ignored (that's maybe also why you put them in the URL). After putting them in the URL, it worked.

    Little tripwire: you may not use the ampersand as standalone in the XML, escape it using & amp ;

    url="jdbc:mysql://localhost:3306/nameOfDB?autoReconnect=true&amp;user=hurrah&amp;password=secret"
  31. Global Data source[ Go to top ]

    I am using Tomcat5.0.28. I have also faced the same problem and could able to solve through the following steps.

    1. Created Datasource using Manager application which in turn create datasource elements in server.xml under <GlobalNamingResources>.

    2. Navigate to D:\jakarta-tomcat-5.0.28\conf\Catalina\localhost\<yourapp>.xml file and inserted the following:

    <ResourceLink name="jdbc/testDataSource" type="javax.sql.DataSource" global="jdbc/testDataSource"/>

    and restarted the Tomcat, it is picking up now. It worked fine even after I deleted the datasource configuration from web.xml of the application.

    Thanks,

    Durga
  32. Tomcat 5.5.4[ Go to top ]

    Philihp... your solution worked perfectly. I used to have the datasource defined in server.xml in a DefaultContext element using Tomcat 5.0; this does not work with 5.5, however. Tried a variety of unsuccessful solutions, but this one works like a charm. Just define the resource params in-line (w/o separating them into discrete elements) within the <context>.xml in catalina/conf/localhost. I guess somehow the XML tags are not being parsed correctly when generating the factory classes.
  33. Tomcat 5.5.4 Example[ Go to top ]

    Could someone please post an example of a working <context>.xml in catalina/conf/localhost.

    ... i have spent waaaay too much time on this. :) thanx.
  34. ROOT web module[ Go to top ]

    Did anyone get anything to work when your web module is deployed on the ROOT context? I can get it connect to ORACLE db if its not on the ROOT but no luck otherwise.

    Like what Cord Thomas said, i had no luck with parsing out the ROOT.xml file into catalina/localhost/ from the web.xml

    Any ideas?

    Kien
  35. Thanks to everybody here I composed a solution that is repeatable in all of my IDE's and test setups. I hope someone finds this useful...

    How to use JNDI for Oracle JDBC Connection Pooling with Tomcat 5.5.4

    Pre-requisite setup:
    Copy ojdbc14.jar (not 'ojdbc14.zip') to the <CATALINA_HOME>/common/lib directory.

    Steps to Implement

    1) In <CATALINA_HOME>/conf/server.xml between <GlobalNamingResources> and </GlobalNamingResources> add:

        <Resource name="jdbc/<alias>"
                  auth="Container"
                  type="javax.sql.DataSource"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
                  url="jdbc:oracle:thin:@<server>:<port>:<sid>"
                  username="<user>"
                  password="<password>"
                  maxActive="20"
                  maxIdle="10"
                  maxWait="-1" />
                  
    example -

      <!-- Global JNDI resources -->
      <GlobalNamingResources>

        <!-- Test entry for demonstration purposes -->
        <Environment name="simpleValue" type="java.lang.Integer" value="30"/>

        <!-- Editable user database that can also be used by
             UserDatabaseRealm to authenticate users -->
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
           description="User database that can be updated and saved"
               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
              
        <Resource name="jdbc/devDb"
                  auth="Container"
                  type="javax.sql.DataSource"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
                  url="jdbc:oracle:thin:@db1.oracle.com:1521:orcl"
                  username="scott"
                  password="tiger"
                  maxActive="20"
                  maxIdle="10"
                  maxWait="-1" />
        
      </GlobalNamingResources>
                  
    2) In <CATALINA_HOME>/conf/context.xml between <Context> and </Context> add:

    <ResourceLink global="jdbc/<alias>" name="jdbc/<alias>" type="javax.sql.DataSource"/>

    example -

    <!-- The contents of this file will be loaded for each web application -->
    <Context>

        <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>META-INF/context.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
    <ResourceLink global="jdbc/devDb" name="jdbc/devDb" type="javax.sql.DataSource"/>
    </Context>


    3) In the <CONTEXT>/WEB-INF/web.xml between <web-app> and </web-app> add:

        <resource-ref>
            <description>Oracle Development Datasource</description>
            <res-ref-name>jdbc/<alias></res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
        
    example -

        <resource-ref>
            <description>Oracle Development Datasource</description>
            <res-ref-name>jdbc/devDb</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
        
    4) Restart Tomcat

    5) In a Java file named Connector.java add the following code

    package com.microdeveloper.db.jndi;

    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;

    public class ConnectionPool {
        String message = "Not Connected";

        public void init() {
            Connection conn = null;
            ResultSet rst = null;
            Statement stmt = null;
            try {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:/comp/env");
                DataSource ds = (DataSource) envContext.lookup("jdbc/devDb");


                if (envContext == null)
                    throw new Exception("Error: No Context");
                if (ds == null)
                    throw new Exception("Error: No DataSource");
                if (ds != null) {
                    conn = ds.getConnection();

                    if (conn != null) {
                        message = "Got Connection " + conn.toString() + ", ";
                        stmt = conn.createStatement();
                        rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
                        if (rst.next()) {
                            message = rst.getString(1);
                        }
                        rst.close();
                        rst = null;
                        stmt.close();
                        stmt = null;
                        conn.close(); // Return to connection pool
                        conn = null; // Make sure we don't close it twice

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // Always make sure result sets and statements are closed,
                // and the connection is returned to the pool
                if (rst != null) {
                    try {
                        rst.close();
                    } catch (SQLException e) {
                        ;
                    }
                    rst = null;
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                        ;
                    }
                    stmt = null;
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        ;
                    }
                    conn = null;
                }
            }

        }

        public String getMessage() {
            return message;
        }

    }

    6) Create a JSP file and add the following code:

    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <html>
    <head><title>JSP Page</title></head>
    <body>

      <%
        com.microdeveloper.db.jndi.ConnectionPool ocp = new com.microdeveloper.db.jndi.ConnectionPool();
        ocp.init();
      %>

      <h2>Results</h2>
        Message: <%= ocp.getMessage() %>
    </body>
    </html>

    7) Compile, deploy, and run. You should see...

    Results
    Message: Success obtaining connection

    8) If not, check the following ...

      Verify database connectivity
    a) TNSPing the database
    b) Connect using the username and password in step 1
    c) Verify the server, sid, and port

    Driver errors (Cannot create JDBC driver of class '' for connect URL 'null'):
    Place the ojdbc14.jar file in the <CATALINA_HOME>\common\lib directory
    Do NOT place the JAR in your <CONTEXT>/WEB-INF/lib directory
    If used with an IDE that auto-deploys, exclude the JAR from the deployment

    Ensure that the resource link (step 2) is in either the <CONTEXT>/META-INF>context.xml file
    - or - the <CATALINA_HOME>/META-INF>context.xml (for global deployment)

      Error messages that 'jdbc' is an unknown context:
      Verify step (3) is complete
  36. Alright, this is my conclusion. For people who is developing web modules and NOT putting into the ROOT context, the jdbc setup can be done and deployed consistently, it has been discussed quite a bit from above. I'll just drop down the to-do to get that bit working:

    1)Before deploying the WAR file to tomcat 5, open up Server.xml file from <tomcat install>/conf folder. In the Global JNDI resources section, add your Resources:

    <!-- Global JNDI resources -->
      <GlobalNamingResources>
        <Resource name="jdbc/DB" scope="Sharable" auth="Container" type="javax.sql.DataSource">
        </Resource>
        <ResourceParams name="jdbc/DB">
          <parameter>
           <name>username</name>
           <value>db_username</value>
          </parameter>
          <parameter>
           <name>password</name>
           <value>*****</value>
          </parameter>
          <parameter>
           <name>driverClassName</name>
           <value>oracle.jdbc.driver.OracleDriver</value>
          </parameter>
          <parameter>
           <name>url</name>
    <value>jdbc:oracle:thin:@db_ip:1521:orca</value>
          </parameter>
          <parameter>
           <name>maxActive</name>
           <value>8</value>
          </parameter>
          <parameter>
           <name>maxIdle</name>
           <value>4</value>
          </parameter>
        </ResourceParams>
      </GlobalNamingResources>

     Save the file.


    2)Open up the file web.xml from your application module WEB-INF/web.xml, make sure you have something like this in there:

      <resource-ref>
        <res-ref-name>jdbc/DB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>

      Save the file.

    3)Open up (create one if does not exist) the file context.xml in your application module META-INF/context.wml and insert:
    <?xml version='1.0' encoding='utf-8'?>
    <Context workDir="work\Catalina\localhost\WEB_APP_NAME" path="/WEB_APP_NAME" docBase="C:/Tomcat5/webapps/WEB_APP_NAME">
       <ResourceLink global="jdbc/DB" name="jdbc/DB" type="javax.sql.DataSource"/>
       <ResourceParams name="jdbc/DB">
          <parameter>
           <name>username</name>
           <value>db_username</value>
          </parameter>
          <parameter>
           <name>password</name>
           <value>****</value>
          </parameter>
          <parameter>
           <name>driverClassName</name>
           <value>oracle.jdbc.driver.OracleDriver</value>
          </parameter>
          <parameter>
           <name>url</name> <value>jdbc:oracle:thin:@db_ip:1521:orca</value>
          </parameter>
          <parameter>
           <name>maxActive</name>
           <value>8</value>
          </parameter>
          <parameter>
           <name>maxIdle</name>
           <value>4</value>
          </parameter>
        </ResourceParams>
    </Context>

      Save the file. You might need to change the docBase entry above to where your web module sits....the complete path...just to be sure.

    4) Make sure you have your relevant jar ( ojdbc14.jar for oracle 9i) in <TOMCAT_INSTALL>/common/lib

    5) Start tomcat server.

    6) It should auto deploy your web module as well as a xml file called <YOU_MODULE_NAME>.xml found in <TOMCAT_INSTALL>/conf/Catalina/localhost. If there isn't Make sure you create one and the content should should have the identical entries as the xml file in META-INF, only the file name is different.

    7) your web module should be able to access DB now




    Ok, now for those who wants to deploy in the ROOT directory of tomcat, its quite similar.

    1)Before starting tomcat, open up server.xml file from <TOMCAT_INSTALL>/conf. In the server.xml file, just BEFORE the </Host> tag, insert a DefaultContext tag as follow:

    <DefaultContext>
      <Resource name="jdbc/DB" scope="Sharable" auth="Container" type="javax.sql.DataSource">
      </Resource>
      <ResourceParams name="jdbc/DB">
         <parameter>
           <name>factory</name> <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
         </parameter>
         <parameter>
           <name>username</name>
           <value>db_username</value>
         </parameter>
         <parameter>
    <name>password</name>
    <value>******</value>
         </parameter>
         <parameter>
            <name>driverClassName</name> <value>oracle.jdbc.driver.OracleDriver</value>
         </parameter>
         <parameter>
            <name>url</name> <value>jdbc:oracle:thin:@db_ip:1521:orca</value>
         </parameter>
         <parameter>
            <name>maxActive</name>
            <value>8</value>
         </parameter>
         <parameter>
          <name>maxIdle</name>
          <value>4</value>
         </parameter>
       </ResourceParams>
     </DefaultContext>

    2)Make sure you have same entry as stated in step 2 to deal with the resource references in WEB-INF/web.xml

    3)Make sure you have the same entry as stated in step 3 above that deals with the context.xml in META-INF folder.

    4)follow step 4, 5 and 6 above as well

    5)You should be able to connect to db now

    After sweat and blood for couple of days, i hope that helps.

    Kien
  37. great example[ Go to top ]

    Thanks so much for such concise and clean instructions. This worked beautifully for me. I am using MySQL and have been frustrated for some time. I think the part I missed all along was putting the configuration in 'context.xml'.

    These directions seem to be generic enough that with some small changes in the vendor specific .jar and url, any database can be configured.
  38. Thanks to Greg Lagnesse[ Go to top ]

    Thanks to Greg Lagnesse for the very detailed whitepaper..

    It helped me to resolve my problem in connecting to Oracle...

    Kudos!!!!

    Noynoy
  39. thanks[ Go to top ]

    I was loosing a lot of time doing the same stuff on Tomcat 5.5 with MySql. Thanks for context.xml needed changes.
  40. It works[ Go to top ]

    i had tried this code for Tomcat 5.5.28 windows , mysql and Eclipse. The only thing is i had changed is and i had followed the other files. thanks Gregg Lagnese for your post
  41. Working example[ Go to top ]

    I need to use JNDI to connect to Oracle database. It took me a lot of time to make it work so I feel it's worth to post this working solution and hopfully it will work for you too.

    Tomcat: 4.1.27
    j2sdk: 1.4.2
    OS: Window XP

    1. Copy classes12.jar file to $CATALINA_HOME/common/lib.
    2. Open your server.xml and search for <Context path="/examples"
    3. Add follow block before <Context path="/examples" and modify value to fit your case.

    <Context path="/applicationName" docBase="applicationName" debug="1" reloadable="true">
    <Resource name="jdbc/testDB" auth="Container"
                   type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/testDB">
       <parameter>
         <name>factory</name>
         <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
       </parameter>
       <parameter>
         <name>driverClassName</name>
         <value>oracle.jdbc.driver.OracleDriver</value>
       </parameter>
       <parameter>
         <name>url</name>
         <value>jdbc:oracle:thin:@127.0.0.1:1521:SID</value>
       </parameter>
       <parameter>
         <name>username</name>
         <value>scott</value>
       </parameter>
       <parameter>
         <name>password</name>
         <value>tiger</value>
       </parameter>
       <parameter>
         <name>maxActive</name>
         <value>30</value>
       </parameter>
       <parameter>
         <name>maxIdle</name>
         <value>10</value>
       </parameter>
       <parameter>
         <name>maxWait</name>
         <value>1000</value>
       </parameter>
    </ResourceParams>
    </Context>

    Restart tomcat server and it works for me.
  42. I just added the following two jars to my WEB-INF/${proj.name}/lob folder restarted tomcat and it worked

    commons-pool-1.2.jar
    commons-dbcp-1.2.1.jar
  43. I found that using the Oracle driver and factory allows per user connections where as the std. factory 'org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory' will not. I also found that the parameters given in the context does not always work depending on the platform, driver, version, and so on, but placing them in the globals always works. You can still restrict which context has access of course.

    When using the Oracle DataSource factory you can leave username and passwords out and pull them in via encrypted means thereby securing the database accounts from intrusions on the Tomcat server. The Oracle DataSource provides a greater degree of flexibility and control as a result.

    I now have a white paper that explains how to reliably set this up here: Tomcat JNDI - Oracle Connection Pooling How-To

    Hope that helps
    .....Gregg
  44. SQL Server 2000, Tomcat 5.5.7[ Go to top ]

    Whew!
    This was semi-painful but the information here was really helpful. Thanks guys!
    This is what worked for me...
    In context.xml:

    <Context ..>
    <Logger .../>

    <Resource name="jdbc/mydb"
    auth="Container"
    type="com.microsoft.jdbcx.sqlserver.SQLServerDataSource"
    factory="com.microsoft.jdbcx.sqlserver.SQLServerDataSourceFactory"
    scope="Shareable"
    user="my_user"
    password="my_pass"
    serverName="127.0.0.1"
    driverClassName="com.microsoft.jdbcx.sqlserver.SQLServerDataSource"
    url="jdbc:microsoft:sqlserver//127.0.0.1:1433;databaseName=mydb;user=my_user;password=my_pass;selectMethod=cursor"/>
    maxActive="15"
    maxIdle="3"
    maxWait="-1"
    removeAbandoned="true"
    logAbandoned="true"
    removeAbandonedTimeout="300" />

    And in web.xml:
    <resource-ref>
         <res-ref-name>jdbc/mydb</res-ref-name> <res-type>com.microsoft.jdbcx.sqlserver.SQLServerDataSource</res-type>
         <res-auth>Container</res-auth>
    </resource-ref>

    Do note:
    1. All classes are explicit Microsoft classes.
    2. Microsoft uses 'user' instead of username for the login attribute.

    Hope this helps the next victim.
  45. To add to my previous posting...[ Go to top ]

    Like many mentioned above, put the SQL Server driver files:
    mssqlserver.jar
    msbase.jar
    msutil.jar

    in <CATALINA_HOME>/shared/lib

    There was no need to add the commons-dbcp, commons-pool and commons-collections to the folder.
  46. Cannot create JDBC driver of class...[ Go to top ]

    I read enough about it on the net and was not successful in getting thro' my problem.

    Environment what i'm using is: Apache 2, Tomcat 5.5,
    Netscape 7.2, MsAccess 2003 on windows 2000 machine.

    I integrated tomcat and apache as apache doesn't
    support jsps. I wrote a JSP called test-db.jsp which
    in turn calls java program TestSQLLoad.java. This
    TestSQLLoad.java performs dattabase operation, fetches
    the data from table and that data is displayed on
    Netscape thro' jsp.

    1. test-db.jsp resides ina directory
    TOMCAT_HOME/webapps/web/JSP. Contents are as follows:

    <%@ page contentType="text/html"
    import="testpkg.TestSQLLoad"%>

    <html>
          <head>
            <title>DB Test</title>
          </head>
          <body>

          <%
            TestSQLLoad tst = new TestSQLLoad();
            tst.init();
          %>

          <h2>Results</h2>
            User -> <%= tst.getUser() %><br/>
            Pwd -> <%= tst.getPassword() %><br/>
            Id -> <%= tst.getID() %>

          </body>
        </html>

    2. TestSQLLoad.java is residing in following
    directory. TOMCAT_HOME/webapps/web/classes/testpkg
    direcotry. Contents of this file are as follows:

    package testpkg;

    import javax.naming.*;
        import javax.sql.*;
        import java.sql.*;

        public class TestSQLLoad
        {
          
         String user = "Not Connected";
         String pwd = "no pwd";
         int id = -1;
         
         public void init() {
          try{
           Context ctx = new InitialContext();
           if(ctx == null ) {
            throw new Exception("Boom - No Context");
           }

    Context envCtx = (Context)
    ctx.lookup("java:comp/env");
           DataSource ds = (DataSource)
    envCtx.lookup("jdbc/db1");

           if (ds != null) {
            Connection conn = ds.getConnection();
            
            if(conn != null) {
             user = "Got Connection "+conn.toString();
             Statement stmt = conn.createStatement();
             String q = "select name, password, id from
    user";
             ResultSet rst = stmt.executeQuery(q);
             if(rst.next()) {
              user=rst.getString(1);
              pwd=rst.getString(2);
              id = rst.getInt(3);
             }
             conn.close();
            }
           }
          }catch(Exception e) {
           e.printStackTrace();
          }
         }

         public String getUser() {
          return user;
         }
         
         public String getPassword() {
          return pwd;
         }
         
         public int getID()
         {
          return id;
         }
        }

    3. I created a jar file using testpkg directory & put
    it in TOMCAT_HOME/common/lib as well as
    TOMCAT_HOME/webapps/web/WEB-INF/lib directory.

    4. I created MsAccess database called db1.mdb and put
    it in TOMCAT_HOME/WEBAPPS/WEB/db1 directory. I created
    a table called 'user' with fields 'name', 'password' and 'ID'.ID is the primary key.

    5. I included following in the server.xml of
    TOMCAT_HOME/conf directory.

    <Context path="/db1" docBase="C:/tomcat/webapps/db1"
                debug="5" reloadable="true"
    crossContext="true">

    <GlobalNamingResources>
      <Resource name="jdbc/db1" auth="Container"
        type="javax.sql.DataSource"

    factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
        driverClassName="sun.jdbc.odbc.JdbcOdbcDrive"
        url="jdbc:odbc://localhost/db1"
    maxActive="20" maxIdle="10" maxWait="-1" />
    </GlobalNamingResources>
    </Context>

    6. I included following in context.xml of
    TOMCAT_HOME/conf directory.

    <DefaultContext>
    <ResourceLink global="jdbc/db1" name="jdbc/db1"
    type="javax.sql.DataSource"/>
    <DefaultContext>

    7. I included following in web.xml of
    TOMCAT_HOME/conf directory.

       <resource-ref>
            <res-ref-name>jdbc/db1</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>

    8. I copied commons-collections-2.1.1.jar,
    commons-dbcp-1.2.1.jar and commons-pool-1.2.jar into
    TOMCAT_HOME/common/lib directory.

    9. I started apache, tomcat and then opened a browser
    and typed http://localhost/web/JSP/test-db.jsp.

    10. I get following on the browser.

    "Results
    User -> Not Connected
    Pwd -> no pwd
    Id -> -1"

    11. On the tomcat window where tomcat is running i'm
    getting following error.

    org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of cla
    ss '' for connect URL 'null'
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDat
    aSource.java:780)
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSo
    urce.java:540)
            at testpkg.TestSQLLoad.init(TestSQLLoad.java:27)
            at org.apache.jsp.JSP.test_002ddb_jsp._jspService(org.apache.jsp.JSP.tes
    t_002ddb_jsp:54)
            at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
            at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper
    .java:325)
            at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:2
    95)
            at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:252)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:173)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
    alve.java:214)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
    alve.java:178)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
    ava:126)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
    ava:105)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
    ve.java:107)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
    a:148)
            at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:306)

            at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:385)
            at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:745)
            at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.ja
    va:675)
            at org.apache.jk.common.SocketConnection.runIt(ChannelSocket.java:868)
            at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadP
    ool.java:684)
            at java.lang.Thread.run(Unknown Source)
    Caused by: java.sql.SQLException: No suitable driver
            at java.sql.DriverManager.getDriver(Unknown Source)
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDat
    aSource.java:773)
            ... 24 more


    Please do let me know if directory structure, the placement of files, the tags etc are correct.

    Do i need a separate driver for Ms Access? If so, is there any free drivers avaialble? How should i use them to solve the above roblem? I already spent 2 complete days setting this up. No luck yet.

    I've rpovided all the information that i can. Please
    help to solve my problem and connect to database thro'
    jsp successfully. Any help in this regard is highly
    appreciated.

    Thanks in advance.
  47. I am having this problem but nothing i've tried in this thread has made any difference.

    I'm using Tomcat 5.0.28 with Eclipse 3.0.1 and mySQL server and the mySQL-connector-java v3.0.1-beta

    ========================================================
    This is a copy of the $CATALINA_HOME/conf/server.xml:

    <?xml version='1.0' encoding='utf-8'?>
    <Server>
      <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
      <GlobalNamingResources>
        <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
       
        <Resource auth="Container" description="User database that can be updated and saved" name="UserDatabase" type="org.apache.catalina.UserDatabase"/>
        <Resource name="jdbc/DBS" auth="Container" type="javax.sql.DataSource"
         factory="org.apache.tomcat.dbcp.BasicDataSourceFactory"
         username="sqluser"
         password="sqluser"
         driverClassName="com.mysql.jdbc.Driver"
         url="jdbc:mysql://localhost:3306/DBS?autoReconnect=true"
         maxWait="1000" removeAbandoned="true"
         maxActive="100" maxIdle="30"
         removeAbandonedTimeout="60" logAbandoned="true"/>

        <ResourceParams name="UserDatabase">
          <parameter>
            <name>factory</name>
            <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
          </parameter>
          <parameter>
            <name>pathname</name>
            <value>conf/tomcat-users.xml</value>
          </parameter>
        </ResourceParams>
        <ResourceParams name="jdbc/DBS">
          <parameter>
            <name>validationQuery</name>
            <value>select * from user;</value>
          </parameter>
          <parameter>
            <name>maxWait</name>
            <value>5000</value>
          </parameter>
          <parameter>
            <name>maxActive</name>
            <value>4</value>
          </parameter>
          <parameter>
            <name>password</name>
            <value>*****</value>
          </parameter>
          <parameter>
            <name>url</name>
            <value>jdbc:mysql://localhost:3306/DBS</value>
          </parameter>
          <parameter>
            <name>driverClassName</name>
            <value>com.mysql.jdbc.Driver</value>
          </parameter>
          <parameter>
            <name>maxIdle</name>
            <value>2</value>
          </parameter>
          <parameter>
            <name>username</name>
            <value>*****</value>
          </parameter>
        </ResourceParams>
      </GlobalNamingResources>

    <ResourceLink global="jdbc/DBS" name="jdbc/DBS" type="javax.sql.DataSource"/>

    <Service name="Catalina">
        <Connector acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" port="8080" redirectPort="8443" maxSpareThreads="75" maxThreads="150" minSpareThreads="25">
        </Connector>
        <Connector port="8009" protocol="AJP/1.3" protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler" redirectPort="8443">
        </Connector>
        <Engine defaultHost="localhost" name="Catalina">
          <Host appBase="webapps" name="localhost">
            <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_log." suffix=".txt" timestamp="true"/>
          </Host>
          <Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
          <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
        </Engine>
      </Service>
    </Server>
    =====================================================

    I have put this in the web.xml file in the web applications web/WEB-INF directory

    <!-- Declare database resource -->
      <resource-ref>
       <description>DB Connection</description>
       <res-ref-name>jdbc/DBS</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
      </resource-ref>

    =======================================================

    I have written a small application in a jsp page which calls this database directly and it works but i want to do it this way so tomcat looks after the connections on my behalf. Can anyone see why i'm getting this error?
  48. Re: Cannot creat JDBC ...[ Go to top ]

    I think the key is creating the context.xml file and putting it in the MET_INF folder.

    An example contents for context.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <Context docBase="MyWebApp" path="/MyWebApp" workDir="work\Catalina\localhost\MyWebApp">
    <!--
    <Resource auth="Container" description="MyFirstDatabase" name="jdbc/MyFirstDatabase" type="javax.sql.DataSource"/>
    <Resource auth="Container" description="MySecondDatabase" name="jdbc/MySecondDatabase" type="javax.sql.DataSource"/>
    -->
    <ResourceLink
                name="jdbc/MyFirstDatabase"
                global="jdbc/MyFirstDatabase"
                type="javax.sql.DataSource"
              />
            <ResourceLink
                name="jdbc/MySecondDatabase"
                global="jdbc/MySecondDatabase"
                type="javax.sql.DataSource"
              />
    </Context>
  49. To establish connection using connection pool for:

    Tomcat 5.0.28
    Microsoft jdbc driver sp3.
    window 2003 server
    sql server 2000


    1. Put the Microsoft jdbc driver jar files, as well as commons-pool-1.2.jar, commons-dbcp-1.2.1.jar, and commons-collections-3.0.jar into $TOMCAT_HOME$\common\lib\

    2. Use the admin page in tomcat (http://localhost:18080/admin) to create a connection pool with the following data

    JNDI Name: jdbc/MyFirstDatabase
    Data Source URL: jdbc:microsoft:sqlserver://localhost:1433;DatabaseName= MyFirstDatabase
    JDBC Driver Class: com.microsoft.jdbc.sqlserver.SQLServerDriver
    User Name: <username>
    password: <password>

    Do this for all your databases (MyFirstDatabase, MySecondDatabase, etc.)

    3. Put a file called Context.xml in $TOMCAT_HOME$\webapps\MyWebApp\META-INF with following contents:

    <?xml version="1.0" encoding="utf-8"?>
    <Context docBase="MyWebApp" path="/MyWebApp" workDir="work\Catalina\localhost\MyWebApp">
    <!--
    <Resource auth="Container" description="MyFirstDatabase" name="jdbc/MyFirstDatabase" type="javax.sql.DataSource"/>
    <Resource auth="Container" description="MySecondDatabase" name="jdbc/MySecondDatabase" type="javax.sql.DataSource"/>
    -->
    <ResourceLink
                name="jdbc/MyFirstDatabase"
                global="jdbc/MyFirstDatabase"
                type="javax.sql.DataSource"
              />
            <ResourceLink
                name="jdbc/MySecondDatabase"
                global="jdbc/MySecondDatabase"
                type="javax.sql.DataSource"
              />
    </Context>

    Put the following code within the <webapp> element of $TOMCAT_HOME$\webapps\MyWebApp \WEB_INF\web.xml:


      <resource-ref>
       <description>jdbc/MySecondDatabase</description>
       <res-ref-name>jdbc/MySecondDatabase</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
      </resource-ref>

        <resource-ref>
       <description>jdbc/MyFirstDatabase</description>
       <res-ref-name>jdbc/MyFirstDatabase</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
      </resource-ref>

     
    Use the following code to get the connection:

        public static Connection getPooledConnection(String dataSource) throws SQLException {
            Connection conn = null;
            try {
                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                DataSource ds = (DataSource) envCtx.lookup(dataSource);
                conn = ds.getConnection();
            }
            catch (NamingException e) {
                logger.error("getPooledConnection Failed to get database connection " + dataSource);
                logger.error(e);
                throw(new SQLException("NamingException in getPooledConnection"));
            }
            return conn;
        }
  50. Help[ Go to top ]

    Can anyone post the steps for connecting to an oracle 9i database using tomcat 5.0.28? Also do i just create a context.xml file because there is none in my conf folder. Cheers.
  51. Re Help[ Go to top ]

    Brian,

    Yep. Just create a file called context.xml and stick it in that folder. Note the post by Christopher Gorres if you want to change it though.

    Good luck and cheers.
  52. Hi, I think I´ve read hundreds of tutorials, mails...

    but it doesn´t work for me, always the same message:

    org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'

    I´ve followed all your steps, but it doesn´t work

    here is what I´ve got:

    ###########################
    conf\server.xml
    ###########################

    <?xml version='1.0' encoding='utf-8'?>
    <Server>
      <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
      <GlobalNamingResources>
        <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
        <Resource auth="Container" description="User database that can be updated and saved" name="UserDatabase" type="org.apache.catalina.UserDatabase"/>
        <ResourceParams name="UserDatabase">
          <parameter>
            <name>factory</name>
            <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
          </parameter>
          <parameter>
            <name>pathname</name>
            <value>conf/tomcat-users.xml</value>
          </parameter>
        </ResourceParams>
        
       <Resource name="jdbc/bddesa"
                  auth="Container"
                  type="javax.sql.DataSource"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
                  url="jdbc:oracle:thin:@10.0.100.6:1521:bddesa"
                  username="rasla"
                  password="****"
                  maxActive="20"
                  maxIdle="10"
                  maxWait="-1" />
        
      </GlobalNamingResources>
      <Service name="Catalina">
        <Connector acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" port="8080" redirectPort="8443" maxSpareThreads="75" maxThreads="150" minSpareThreads="25">
        </Connector>
        <Connector port="8009" protocol="AJP/1.3" protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler" redirectPort="8443">
        </Connector>
        <Engine defaultHost="localhost" name="Catalina">
          <Host appBase="webapps" name="localhost">
            <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_log." suffix=".txt" timestamp="true"/>
          </Host>
          <Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
          <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
        </Engine>
      </Service>
    </Server>




    ##################
    ROOT/WEB-INF/web.xml
    ###################

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!--
      Copyright 2004 The Apache Software Foundation

      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    -->

    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
        version="2.4">

      <display-name>Welcome to Tomcat</display-name>
      <description>
         Welcome to Tomcat
      </description>


    <!-- JSPC servlet mappings start -->

        <servlet>
            <servlet-name>org.apache.jsp.index_jsp</servlet-name>
            <servlet-class>org.apache.jsp.index_jsp</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>org.apache.jsp.index_jsp</servlet-name>
            <url-pattern>/index.jsp</url-pattern>
        </servlet-mapping>

    <!-- JSPC servlet mappings end -->




    <resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/bddesa</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>



    </web-app>



    ######################
    Catalina/localhost/_/META-INF/context.xml
    #####################
    <?xml version="1.0" encoding="utf-8"?>
    <Context displayName="Welcome to Tomcat" docBase="C:\Archivos de programa\Apache Software Foundation\Tomcat 5.0\webapps\ROOT" path="" workDir="work\Catalina\localhost\_">
    <!--
    <Resource auth="Container" description="MyFirstDatabase" name="jdbc/MyFirstDatabase" type="javax.sql.DataSource"/>
    <Resource auth="Container" description="MySecondDatabase" name="jdbc/MySecondDatabase" type="javax.sql.DataSource"/>
    -->
    <ResourceLink
                name="jdbc/bddesa"
                global="jdbc/bddesa"
                type="javax.sql.DataSource"
              />
    </Context>




    BUT IT DOESN´T WORK!!!!!!!!!

    I´m frustated and desperated :-(

    any help please?

    thanks
  53. 0. Shutdown tomcat.

    1. If not already present, copy the following (recent) versions of the mysql connector and commons-* jars
    to $TOMCAT_HOME/common/lib. Delete any old ones.

    mysql-connector-java-3.0.14-production-bin.jar
    commons-collections-2.1.1.jar
    commons-dbcp-1.2.1.jar

    2. Ignore the advice in the tomcat-5 docs on jakarta.apache.org telling you to modify server.xml. Tomcat 5 uses a minimalist server.xml and now does application-specific configuration in separate files. If you have mucked up your server.xml either by hand editing or using the tomcat manager app, start fresh. Shutdown tomcat and copy a new minimalist server.xml in place.

    If your webapp is called foo, create a file $TOMCAT_HOME/conf/Catalina/localhost/foo.xml. Save a copy of foo.xml in another location - the working copy is deleted if you undeploy foo using the tomcat manager.

    Now, the resource info mentioned above a few times should be pasted within this context!

    See the following:
    http://forums.devshed.com/t120081/s.html
  54. UI[ Go to top ]

    User the /admin app to set the datasource globally and the local application
  55. Check you have DBCP[ Go to top ]

    Just thought I'd add that, for me, all of the above (while ultimately accurate) only worked after I realized that I didn't seem to have any DBCP JARs included in my Tomcat 5.5 installation.

    Perhaps there is a release out there that doesn't include commons-dbcp.jar by default?

    Anyway, just one more thing to check for those having difficulties...
  56. Hello
    here is configuration for my DataSource in server.xml
    ...........
       <parameter>
         <name>maxActive</name>
         <value>20</value>
       </parameter>
       <parameter>
         <name>maxIdle</name>
         <value>10</value>
       </parameter>
       <parameter>
         <name>maxWait</name>
         <value>-1</value>
       </parameter>
    <parameter>
    <name>removeAbandoned</name>
    <value>true</value>
    </parameter>
    <parameter>
    <name>removeAbandonedTimeout</name>
    <value>60</value>
    </parameter>
    <parameter>
    <name>logAbandoned</name>
    <value>true</value>
    </parameter>
    ...........

    I tested the case "the number of connection reached to maxActive" with the codes JSP following
    <%
    Context initContext = new InitialContext();
    javax.sql.DataSource ds = (javax.sql.DataSource)initContext.lookup("java:/comp/env/jdbc/fermatel");
    for(int i = 0; i < 21; i++) {
    out.println("<br>Trying Connection " + i );
    System.out.print("<br>Trying Connection " + i );
    Connection conn = ds.getConnection();
    Statement s= conn.createStatement();
    ResultSet rs1 = s.executeQuery("select 1 from dual");
    rs1.next();
    rs1.close();
    s.close();
    // conn.close(); --> no disconnect
    // conn = null;
    out.println("--> Connection succès " + i );
    System.out.println("--> Connection succès " + i );
    }
    %>

    The standard output is:
    ------------------
    <br>Trying Connection 0AbandonedObjectPool is used (org.apache.commons.dbcp.Aban
    donedObjectPool@1f02b85)
       LogAbandoned: true
       RemoveAbandoned: true
       RemoveAbandonedTimeout: 60
    --> Connection succÞs 0
    <br>Trying Connection 1--> Connection succÞs 1
    <br>Trying Connection 2--> Connection succÞs 2
    <br>Trying Connection 3--> Connection succÞs 3
    <br>Trying Connection 4--> Connection succÞs 4
    <br>Trying Connection 5--> Connection succÞs 5
    <br>Trying Connection 6--> Connection succÞs 6
    <br>Trying Connection 7--> Connection succÞs 7
    <br>Trying Connection 8--> Connection succÞs 8
    <br>Trying Connection 9--> Connection succÞs 9
    <br>Trying Connection 10--> Connection succÞs 10
    <br>Trying Connection 11--> Connection succÞs 11
    <br>Trying Connection 12--> Connection succÞs 12
    <br>Trying Connection 13--> Connection succÞs 13
    <br>Trying Connection 14--> Connection succÞs 14
    <br>Trying Connection 15--> Connection succÞs 15
    <br>Trying Connection 16--> Connection succÞs 16
    <br>Trying Connection 17--> Connection succÞs 17
    <br>Trying Connection 18--> Connection succÞs 18
    <br>Trying Connection 19--> Connection succÞs 19
    <br>Trying Connection 20
    ------------------
    It is normal if this JSP is blocked on 21rd connection (because all 20 connections in pool are holded on). But after 60seconds (=removeAbandoned), this JSP is always blocked! I am worry about it. I wonder if there is mechanism who can set available one connection that is idle in 60seconds!

    thanks a lot
    best regards!
    Hai
  57. I run into this before and I think I've finally found the problem! Short answer: the servlet.xml may only import a separate context.xml correctly on the initial deployment, ignoring new JNDI resources w/ resource params added later.

    In my case, when a second JNDI resource was added to my context.xml file, I could get the resource but it would complain about the "null" URL configuration, even after restarting Tomcat. I then noticed in my server.xml that the new JNDI resource info didn't seem to be there.

    Upon manually removing the imported Context from the servet.xml and restarting tomcat, it was reimported correctly and my connections worked perfectly! I would imagine "removing" and "redploying" the webapp using the manager application would have the same effect but I haven't tested that.
  58. The key fix for me was to move the "driverClassName" and "url" Parameters to attributes of the <Resource> tag.

    <Resource name="jdbc/juddiDB"
    auth="Container"
    type="javax.sql.DataSource"
    url="jdbc:mysql://localhost:3306/juddi?autoReconnect=true"
    driverClassName="org.gjt.mm.mysql.Driver"/>
  59. Found a solution for this..[ Go to top ]

    After banging my head against the wall for hours upon hours I've found the solution. I had to uninstall Tomcat 5.0.28 and install 5.5. You'll need to download the compatibility download which is available from Apache's download site under Tomcat 5.5.

    Here's the steps I took to correct the problem:

    1. You don't want to modify server.xml.
    2. Copy JDBC driver, dbcp and collections jars to common/lib.
    3. Add the following to your web.xml in your application:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

     <resource-ref>
          <description>DB Connection</description>
          <res-ref-name>jdbc/dbTest</res-ref-name>
          <res-type>javax.sql.DataSource</res-type>
          <res-auth>Container</res-auth>
      </resource-ref>
    </web-app>

    4. Create new context.xml under META-INF and paste the following:
    <?xml version='1.0' encoding='utf-8'?>
        <Context crossContext="true" debug="5" docBase="dbtest" path="/dbtest" reloadable="true">
        <Logger className="org.apache.catalina.logger.FileLogger"
                 prefix="localhost_realtorApp_log." suffix=".txt"
                 timestamp="true"/>
       <Resource
          name="jdbc/dbTest"
          auth="Container"
          type="javax.sql.DataSource"
          username="root"
          password="XXXX"
          driverClassName="com.mysql.jdbc.Driver"
          maxWait="5000"
          url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"
          maxActive="4"
          maxIdle="2"/>
       </Context>

    5. Create the JSP page:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>


    <sql:query var="rs" dataSource="jdbc/dbTest">
    select id, foo, bar from testdata
    </sql:query>

    <html>
      <head>
        <title>DB Test</title>
      </head>
      <body>

      <h2>Results</h2>
      
    <c:forEach var="row" items="${rs.rows}">
        Foo ${row.foo}<br/>
        Bar ${row.bar}<br/>
    </c:forEach>

      </body>
    </html>

    6. Make sure the database and table exists in mysql with some data.

    7. Your result in the jsp should be:

    Results
    Foo hello
    Bar 12345
  60. Nothing works[ Go to top ]

    I have tried all of the solutions mentioned here and not a one of them works. I am running TOmcat 5.5 on XP trying to connect to Oracle 8i. Either I get the same error mentioned or I get an operation not supported when I try to get a connection.

    I did try the META-INF folder method, but Tomcat doesn't seem to have this folder anywhere. WHen I put one below my webapp folder, the web app in question is no longer accessible.

    Any help would be appreicated.

    Thanks in advance.
  61. Hi friends, I too tired with this and find out the solution. please go through the following website.

    http://www.ericsson.com/mobilityworld/sub/open/technologies/open_development_tips/docs/odt_tomcat_db_connection
  62. Just wanted to say thanks. This helped me with setting things up. I am also including server.xml extracts. Hopefully this will help some others with the same problem.

    --------------server.xml--------------------------
    ...

     <!-- Global JNDI resources -->
      <GlobalNamingResources>

        <!-- Test entry for demonstration purposes -->
        <Environment name="simpleValue" type="java.lang.Integer" value="30"/>

        <!-- Editable user database that can also be used by
             UserDatabaseRealm to authenticate users -->
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
           description="User database that can be updated and saved"
               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />

        <Resource name="jdbc/testDB" auth="Container"
         type="javax.sql.DataSource"
         driverClassName="oracle.jdbc.OracleDriver"
         url="jdbc:oracle:thin:@123.123.123.123:1521:testDB" username="db_user"
         password="secret" maxActive="20" maxIdle="10" maxWait="-1" />

      </GlobalNamingResources>
    ...
    ...
    ...

          <Context docBase="<TOMCAT_INSTALL_PATH>/webapps/WebApplication" path="/WebApplication" reloadable="true" source="com.ibm.wtp.web.server:WebApplication">
             <ResourceLink global="jdbc/testDB" name="testdatabase"
              type="java.sql.DataSource" />

          </Context>

          </Host>

        </Engine>

      </Service>

    ---------------------------------

    Regards,
    Kobus
  63. Still not working[ Go to top ]

    I am getting "Cannot create JDBC driver of class '' for connect URL 'null'" all the time. I've tried almost everything and nothing worked for me. I use XP, MSSQL 200 with jtds driver on Tomcat 4.1. I use eclipse IDE. Any help would be appreciated.
  64. I am using Tomcat 5.5 and Mysql 4.x version 1. In the /commom/lib, there should not be a conflict of the driver jars. For eg: in mine i had both mysql-connector-java-3.1.8-bin.jar and mysql-connector-java-3.1.8-ga-bin.jar. I removed the latter and it started working. 2. Remove all those huge and complicated markup that you have accumulated in different places like the entries in server.xml, META-INF/context.xml,and in the tomcat folders. Let us start fresh (please note that this is only for TOMCAT 5.5 and above) within your definition include your resource link like the example below: Please note that to not include the FACTORY attribute, as this is automatically picked up by tomcat 5.5 based on the type of datasource, which here is java.sql.Datasource. Therefore it automatically uses the tomcat-internal dbcp-factory. Also for tomcat 5.5 this is the recommended way to include resource definitions,unlike the long version where we write the resource params in a different element. If you would like to add more of the resource params, follow the same pattern here i.e. ="".../> 3. Restart and see if it works, if still there is a problem in the DOCBASE attribute of the context element, replace the path with the absolute path to your project folder. GOOD LUCK!
  65. Adding all the connection attributes into element as Bob suggested worked perfectly for Tomcat 5.5.* and MySQL combination. I have also implemented all the other optional attributes available from Tomcat JNDI HOW-TO page in the resource element. Here is my example for your reference. In $TOMCAT_HOME/conf/server.xml add the context element defining your web application as follow: You may also want to add the resource-ref in the web.xml: DB Connection jdbc/MySQLDB javax.sql.DataSource Container
  66. Greetings, If you have Tomcat 5.5 and above, don't worry about any other thing except /conf/context.xml. 1) Add your resources to /conf/context.xml. 2) Ofcourse you should add resource-ref in web.xml I didn't add anything in server.xml and META-INF/... I used a single /conf/context.xml to add Oracle, Sybase , AS400 and MQ connections. Thanks.
  67. Also, make sure you put resource jar files in common/lib. Dont duplicate. Don't put naming*.jar files in your WebApp. I struggled for a day becuase of naming*.jar files at duplicate places. Thanks. Kanuugla.
  68. Tomcat Vesrion vs. config.xml format[ Go to top ]

    This error is also caused by difference in format of the application context.xml file you put $TOMCAT_HOME$/conf/catalina/localhost directory. So make sure that this format is consistent with your Tomcat version. I was getting this error with following app.xml file and Tomcat 5.0. <!-- development DB: --> I just reformatted this as following and it worked. url jdbc:jtds:sqlserver://db:1433/schema1;user=username;password=passwd maxIdle 30 maxActive 200 driverClassName net.sourceforge.jtds.jdbc.Driver maxWait 10000 removeAbandoned true testWhileIdle true numTestsPerEvictionRun 100 minEvictableIdleTimeMillis 600000 factory org.apache.commons.dbcp.BasicDataSourceFactory logAbandoned true removeAbandonedTimeout 30 timeBetweenEvictionRunsMillis 300000 username username password passwd
  69. There are like eight different problems going on here with eight different solutions. And every six posts there is the obligatory "i put my xxx-driver.jar file in .../lib and it worked!" message. Driving me nuts just reading it. And now I'm contributing to the madness. Sigh... I'm not even going to bother explaining the problem I have, cause I know it'll just generate more noise. Good luck to each and every one of you. Someday the apache people will clarify their documentation, I hope. We all hope. It's all we can do, besides cross our fingers, make random config file edits, move files around arbitrarily, and curse our computers to death.
  70. Hi, Found the solution best described in below link. http://wiki.apache.org/tomcat/UsingDataSources Im using tomcat 6.0.18 on vista and oracle 10g. Hope this Infomation might help someone. 1. comment following line in TOMCAT_HOME\conf\context.xml WEB-INF/web.xml 2. copy following in ur web applications META-INF\context.xml <!--?xml version='1.0' encoding='utf-8'?--> 3. no need to edit TOMCAT_HOME\conf\server.xml or WEB-INF\web.xml. Hope this helps bye
  71. Made it to work..[ Go to top ]

    My problem was that I was always updating the context.xml in META-INF. However tomcat is looking inside conf\Catalina\localhost\.xml for the connection details, which in my case did not have any details. So here is the solution: 1] Either copy META-INF\context.xml to conf\Catalina\localhost\.xml OR 2] Directly edit conf\Catalina\localhost\.xml OR 3] If you still want to put your stuff in context.xml, then undeploy the app and deploy it again. This ensures that context.xml gets copied over to conf. Hope this helps Bhay
  72. If the problem still persists even after adding ojdbc14.jar and adding corresponding entry in Context.xml / server.xml and adding entry in web.xml, then the problem might be due to the Role under which the App is running.

    I had this issue and I was not able to run as I was running as guest. When I deployed my code in tomcat under manager and started the app, it started to work fine.

     

  73. nice info[ Go to top ]

    tanks you for your info. nice article i like this blog. foredi

  74. Izin Usaha[ Go to top ]

    Nice article for my izin usaha

  75. Hi, I am having the same problem. I am getting the following error when navigating to: http://localhost:8080/publisher/news.rss for my web app.

    I am using Tomcat 7.0, mysql 5.5,mysql-connector-java-5.1.25-bin.jar, eclipse-jee-juno-SR2-win32.

    I have a publisher.xml in my project :

    <Context path="/publisher" docBase="I:\Eclispe work\publisher\WebContent"> 

    <Resource name="datasource"             type="javax.sql.DataSource"            auth="Container"            maxActive="10"            maxIdle="3"             maxWait="10000"            username="publisher"             password="publisher"             driverClassName="com.mysql.jdbc.Driver"            url="jdbc:mysql://localhost:3306/publisher?autoReconnect=true" /></Context>

     

    I have also a context.xml in C:\Tomcat 7.0\conf directory with contents:

    <!--  Licensed to the Apache Software Foundation (ASF) under one or more  contributor license agreements.  See the NOTICE file distributed with  this work for additional information regarding copyright ownership.  The ASF licenses this file to You under the Apache License, Version 2.0  (the "License"); you may not use this file except in compliance with  the License.  You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.--><!-- The contents of this file will be loaded for each web application --><Context>
        <!-- Default set of monitored resources -->    <WatchedResource>WEB-INF/web.xml</WatchedResource>
        <!-- Uncomment this to disable session persistence across Tomcat restarts -->    <!--    <Manager pathname="" />    -->
        <!-- Uncomment this to enable Comet connection tacking (provides events         on session expiration as well as webapp lifecycle) -->    <!--    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />    -->
    </Context>

     

    my web.xml is:

    <?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>publisher</display-name>  <welcome-file-list>  <welcome-file>home.jsp</welcome-file>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet>      <servlet-name>news-feed</servlet-name>      <servlet-class>publisher.web.NewsFeedServlet</servlet-class>   </servlet>   <servlet-mapping>      <servlet-name>news-feed</servlet-name>      <url-pattern>/news.rss</url-pattern>   </servlet-mapping>   <listener>   <listener-class>publisher.web.Init</listener-class>   </listener>   </web-app>

    my NewsFeedServlet.java is:

    package publisher.web;

    import java.io.*;


    import java.sql.*;
    import java.util.*;
    import java.util.Date;

    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.sql.*;

    import org.apache.log4j.*;

    import com.sun.syndication.feed.synd.*;
    import com.sun.syndication.io.*;


    public class NewsFeedServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(this.getClass());
    private static DataSource dataSource;

    public static void setDataSource(DataSource dataSource)
    {
    NewsFeedServlet.dataSource=dataSource;
    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // TODO Auto-generated method stub
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType("rss_2.0");
    feed.setTitle("My Local News Feed");
    feed.setLink("http://localhost:8080/publisher/");
    feed.setPublishedDate(new Date());
    feed.setDescription("This feed was created using ROME");
    List<SyndEntry> entries = new ArrayList<SyndEntry>();

    try{

    Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select * from news_item");
    while(resultSet.next()){
    String title = resultSet.getString("title");
    String url = resultSet.getString("url");
    Date pDate = resultSet.getDate("pubDate");
    //System.out.print(pDate);
    //logger.debug(pDate);
    SyndEntry entry= new SyndEntryImpl();
    entry.setTitle(title);
    entry.setLink(url);
    entry.setPublishedDate(pDate);
    entries.add(entry);
    }
    connection.close();
    } catch (SQLException e){
    throw new ServletException(e);
    }
    resp.setContentType("text/xml");
    feed.setEntries(entries);
    Writer writer = resp.getWriter();
    SyndFeedOutput output = new SyndFeedOutput();
    try{
    output.output(feed, writer);

    }catch(FeedException e){
    logger.error("",e);
    }

    }

    }

     

    And Init.java is:

    package publisher.web;

    import javax.naming.*;


    import javax.servlet.*;
    import javax.sql.*;

    import org.apache.log4j.*;

    public class Init implements ServletContextListener {
    private Logger logger = Logger.getLogger(this.getClass());


    private void contextInitialized2(ServletContext servletContext)
    throws Exception {
    InitialContext enc = new InitialContext();
    Context compContext = (Context) enc.lookup("java:comp/env");
    DataSource dataSource = (DataSource) compContext.lookup("datasource");
    NewsFeedServlet.setDataSource(dataSource);
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    // TODO Auto-generated method stub
    ServletContext servletContext = sce.getServletContext();
    try {
    contextInitialized2(servletContext);
    }
    catch (Exception e)
    {
    logger.error("Initialization failed.", e);
    throw new RuntimeException(e);
    }
    logger.debug("Initialization succeeded.");

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    // TODO Auto-generated method stub

    }

    }

     

    I have done a lot of googling but not getting any solution. I dont konw where is my problem and what is the solution. So plz help me out. Any help is greatly appreciated. Thanks in advance....

  76. thanks for the rest comment[ Go to top ]

    its so many comments here, let me say thanks for the nice article, i hope i can fix it by may self

    Download software gratis