Bind JNDI data source in tomcat?

Is it possible to programmatically bind a DataSource to Tomcat 6 JNDI?

I want to create a DataSource on the fly and then make it available through JNDI (e.g. for ColdFusion).

This is what I have:

public void bindToConext(DataSource dataSource) throws NamingException, SQLException { Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); envContext.bind("jdbc/mydatasource", dataSource); } 

But I get this exception:

 javax.naming.OperationNotSupportedException: Context is read only 

Is there any work?

+5
source share
2 answers

Well, that was not possible, because the tomcat context becomes read-only after startup.

So what we did was use SimpleJNDI, which is a memory context (more like an illustrious HashMap), and it worked for us.

He needs the jndi.properties file, which should be in the class path, and where you define the directory in which to look for resources and the initial factory context

 java.naming.factory.initial=org.osjava.sj.SimpleContextFactory org.osjava.sj.root=some/relative/path org.osjava.jndi.delimiter=/ org.osjava.sj.jndi.shared=true 

To bind to ColdFusion, we first create a data source and then bind it to the context:

 DataSource ds = ... Context c = new InitialContext(); c.bind( "jdbc/my/blah/"+var , ds ); ... 

Then, using the CF admin api, we create a JNDI type CF data source using jndiname

+3
source

Tomcat's working context is java: comp / env. This context is read-only. But you can create your own contexts using the Tomcat JNDI Implementation, as long as you keep yourself out of "java: comp / env".

 Context ctx = new InitialContext() ctx.createSubcontext("any_name").createSubcontext("any_sub_name"); ctx.bind("any_name/any_sub_name/myDataSource", myDataSource); 

By default, Tomcat contexts are shared, so the DataSource is retrieved from anywhere in your application this way:

 Context ctx = new InitialContext() DataSource ds = (DataSource)ctx.lookup("any_name/any_sub_name/myDataSource"); 
+1
source

All Articles