• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cannot Connect to database using datasource realm

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Help needed,anyone there,really stuck for couple of days now.
I'm trying to use datasource realm,but cannot connect to the database. Here's the code . I'm using Eclipse IDE.
1. First of all the login page :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="com.example.model.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page for Examples</title>
<body bgcolor="white">
<%
String result = request.getParameter("result");
if(result == null)
result = "";
if (result.equalsIgnoreCase("false"))
{
%>
<span style="color: red">
Wrong user name or password <br>
</span>
<%
}
%>

<form method="POST" action="j_security_check" >
<table border="0" cellspacing="5">
<tr>
<th align="right">Username:</th>
<td align="left"><input type="text" name="j_username"></td>
</tr>
<tr>
<th align="right">Password:</th>
<td align="left"><input type="password" name="j_password"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Log in"></td>
<td align="left"><input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>

2.Here's the web.xml :


<?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_2_5.xsd" version="2.5">
<session-config>
<session-timeout>15</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<security-role>
<role-name>boss</role-name>
</security-role>
<security-role>
<role-name>manager</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected area</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>boss</role-name>
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login.jsp?result=false</form-error-page>
</form-login-config>
</login-config>
</web-app>


3. Here's the context.xml (which I have placed inside the META_INF)


<context>

<!-- Specify a JDBC datasource -->
<Resource name="jdbc/testdb" auth="Container"
type="javax.sql.DataSource"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db1"
maxActive="10"
maxIdle="4" />


<Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/testdb"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

</context>
Please Note: I've tried using this code even in server.xml(still no go)

4. I've created a class for DAtabase Connection called DBConn.java(Ya, I'm using JNDI)

package com.example.model;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBConn {
public static Connection connect()throws SQLException, NamingException
{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource dataSource = (DataSource)envContext.lookup("jdbc/testdb");
Connection connection = dataSource.getConnection();
return connection;
}
}

..... I've even created the database tables users & user_roles in mysql
.....When I run the program the login page appears properly,But when I try to login with the "CORRECT" username & password it gives this error :

SEVERE: Exception performing authentication
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:774)
at org.apache.naming.NamingContext.lookup(NamingContext.java:157)
at org.apache.catalina.realm.DataSourceRealm.open(DataSourceRealm.java:397)
at org.apache.catalina.realm.DataSourceRealm.authenticate(DataSourceRealm.java:287)
at org.apache.catalina.authenticator.FormAuthenticator.authenticate(FormAuthenticator.java:259)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:454)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

.. I think this is happening because there is no way by which DataSource dataSource = (DataSource)envContext.lookup("jdbc/testdb"); in DBConn.java is being called... But How & where do I initialize my DBConn.java's object.. How would this class be called....Please Help I'm really really stuck !!

Thank you.
Regards,
Piyush Sah

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,,

see this link i think there is wrong in your ContextLookup Only..
http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html

https://coderanch.com/t/442367/Tomcat/Name-jdbc-not-bound-Context
 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

ramakrishna rayudu wrote:Hi,,

see this link i think there is wrong in your ContextLookup Only..
http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html

https://coderanch.com/t/442367/Tomcat/Name-jdbc-not-bound-Context



Dear Ramakrishna ,
Thank You for your reply.But the contextLookup has no issues at all. Because I use the same code, for other database things like insert ,update etc.. it works absolutely fine (i.e. when I dont use Realms)..So I suppose the problem is elsewhere.

Regards,
Piyush Sah
 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is anyone there to resolve this error??
 
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's a bit more than my fuzzy eyes can make sense of this early in the morning, but on the surface, things seem OK.

I'm not sure, however if you're expecting to write user application code that uses the DataSourceRealm directly. If so, don't, since the Realm is part of Tomcat, not part of the application and there's nothing in the J2EE standard interface that supports or requires application code to talk directly to the Realm.

Most likely, however, you're running afoul of the WTP Eclipse plugin. I don't like WTP, and this is one reason why - it does dirty things with server.xml and you frequently have to band on it with a hammer to get changes in your web server configuration to actually take effect.
 
author
Posts: 5856
7
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This looks like a Tomcat question and has nothing to do with Eclipse. Moving
 
Ranch Hand
Posts: 338
Scala Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI,

Read this page from start to end without missing a single word..

Check this link, do it step by step :
http://tomcat.apache.org/tomcat-4.1-doc/realm-howto.html#JNDIRealm

I think you should get solution!!!
 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
tried to do a simple program to connect to the database & this is what happens
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
1. DBTest.java


package com.example.model;

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

import java.sql.*;

public class DBTest {
String foo = " Foo Not Connected";
String bar = "Bar not connected";

public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");

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

if (ds != null) {
Connection conn = ds.getConnection();

if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select username from login");
if(rst.next()) {
foo=rst.getString(1);
// bar=rst.getString(2);
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}

public String getFoo() { return foo; }
// public String getBar() { return bar;}
}

2. Server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
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.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">

<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- 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" />
</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">

<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->


<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="10000" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->

<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">

<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->

<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->

<!--<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>-->

<Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/testdb"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>


<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->


<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">

<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->

<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_DBTest_log." suffix=".txt" timestamp="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>

<!-- 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 -1 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>

<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>

<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value>root</value>
</parameter>

<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>

<!-- The JDBC connection url for connecting to your MySQL dB.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/db1</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
</Server>

is this the correct place to put the <context >??
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can make your code and XML more readably by using the "Code" button on the message editor to wrap them with special tags.

When you get a "Cannot create JDBC driver of class ''" message that means that Tomcat could not create the DBCP connection pool. So it's not in your application.

Usually, it means that the connection URL is malformed, although you can get it from improper captialization of certain resource attribute names as well. So take a very close look at the <Resource> definition. This stuff can be very hard to find.
 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I coded the entire thing in the server.xml(tomcat 7.0/conf/lib)
Here's the Server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
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.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">

<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- 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" />
</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">

<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->


<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="10000" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->

<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">

<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->

<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>

<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">

<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->

<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">

<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="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>

<!-- 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 -1 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>

<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>

<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value>root</value>
</parameter>

<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>

<!-- The JDBC connection url for connecting to your MySQL dB.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/javatest</value>
</parameter>
</ResourceParams>
</Context>

</Host>
</Engine>
</Service>
</Server>

2. Web.xml is unchanged

3.test.jsp


<%@page import="foo.DBTest" %>
<html>
<head>
<title>DB Test</title>
</head>
<body>

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

<h2>Results</h2>
Foo <%= tst.getFoo() %><br/>
Bar <%= tst.getBar() %>

</body>
</html>

4. DBTest.java

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

public class DBTest {

String foo = "Not Connected";
int bar = -1;

public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )throw new Exception("Boom - No Context");

DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
System.out.println("Hello");
if (ds != null) {
Connection conn = ds.getConnection();


if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select id, foo, bar from testdata");
if(rst.next()) {
foo=rst.getString(2);
bar=rst.getInt(3);
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}

public String getFoo() { return foo; }
public int getBar() { return bar;}
}

Now I know, the jsp is calling my DBTest.java I've done a println("Hello") and that executes. But as soon as Connection conn = ds.getConnection();
is executed it gives the following error :
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'

Help guys I'm really fed up now !!
 
Pankaj Shet
Ranch Hand
Posts: 338
Scala Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey,check this link,

did you add JDBC Driver's jar into $CATALINA_HOME/lib.?
did you configure MYSQL Db??


http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html#JNDI_Resource_Naming_and_Realm_Interaction

and

also to understand Context deeper:

http://tomcat.apache.org/tomcat-7.0-doc/config/context.html


I think you should do it according to that link so that you can understand it
create another small project and do it according to the above document without missing a single step..!!
once it is successful,

You may configure your project or modify this new project to suit your needs..!!!

do it step by step... read it from top to bottom...!!!
I know you people will be able to achieve it!!!
 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Finally got my code up running
Here are the changes I did :
1. I removed the context.xml
2. Inside the server.xml pasted the following code

<Resource name="jdbc/testdb" auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="30000"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db1? autoReconnect=true"/>

Note : This has to be inside <GlobalNamingResources>

3. here's the web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">

<security-constraint>

<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>/protected/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>boss</role-name>
<role-name>manager</role-name>
</auth-constraint>

</security-constraint>

<!-- Default login configuration uses form-based authentication -->
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/protected/login.jsp</form-login-page>
<form-error-page>/protected/error.jsp</form-error-page>
</form-login-config>
</login-config>

<!-- Security roles referenced by this web application -->
<security-role>
<role-name>boss</role-name>
</security-role>
<security-role>
<role-name>manager</role-name>
</security-role>
</web-app>
4. And the most important change : Pasted mysql-connector-java-3.1.6-bin.jar inside the Tomcat7.0/lib folder instead of mysql-connector-java-5.0.8-bin.jar(which I was using earlier)

The code now works absolutely fine

 
piyush sah
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And one more thing also put

<Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/testdb"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

inside the <Engine> tag in server.xml.
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

piyush sah wrote:And one more thing also put

<Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/testdb"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name"/>

inside the <Engine> tag in server.xml.



Actually, this depends. Most times I work with systems that operate against several different security Realms, depending on which app is being secured. So I normally have the Realm definition in the webapp Context, not in server.xml
 
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
piyush,

When you create a context.xml in META-INF/ of your webapp, it gets copied to conf/Catalina/localhost.

I was going to suggest when you stop Tomcat, to remove the associated context name from the conf/Catalina/localhost and then restart.

Tomcat doesn't delete the context in conf/Catalina/localhost when you are using an exploed webapp - so if you are editing the context in META-INF Tomcat doesn't pick up the change.

It does when you are deploying a war file. Perhaps your context in conf/Catalina/localhost was holding on to the wrong jdbc name.

I personally wouldn't place datasource stuff in server.xml. What if each of your webapps wanted to connect to different datasources?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic