I have a datasource set in my Jetty.xml file that looks like this:
<New id="MySQL_DS" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/MySQL_DS</Arg>
<Arg>
<New class="com.mchange.v2.c3p0.ComboPooledDataSource">
<Set name="driverClass">com.mysql.jdbc.Driver</Set>
<Set name="jdbcUrl">jdbc:mysql:[IP]</Set>
<Set name="user">[USER]</Set>
<Set name="password">[PASSWORD]</Set>
<Set name="checkoutTimeout">5000</Set>
<Set name="initialPoolSize">3</Set>
<Set name="maxIdleTime">3600</Set>
<Set name="maxPoolSize">50</Set>
<Set name="minPoolSize">1</Set>
<Set name="maxStatements">200</Set>
<Set name="maxConnectionAge">0</Set>
<Set name="acquireIncrement">3</Set>
</New>
</Arg>
</New>
It is defined in my web.xml like so:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MySQL_DS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
And I bind to my datasource like this in my servlet code:
InitialContext ctx = new InitialContext();
_dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/MySQL_DS");
My question is:
I need to have 4 servlet using this context lookup, on the same datasource. Is such a thing even possible?
I mean, can multiple servlets bind to the same datasource, or must each servlet have their own one?
I'm asking this because I have one servlet that is working correctly but another one throws a javax.naming.NameNotFoundException (remaining name jdbc/MySQL_DS).
Thanks!
As far as I know, you shouldn't have to specify unique data sources for each servlet.
I'm working on a Java EE web application that has multiple servlets in it that all use one data source for connecting to the DB. This web application uses Oracle as the back-end and WebLogic Server as the application server.
In this web application's architecture, there's a dedicated class for connecting to the DB. All of the servlets invoke this class to get a connection to the DB.
This connection class has the following lines in the constructor (similar to yours above)...
InitialContext ic=new InitialContext();
DataSource ds=(DataSource) ic.lookup("jdbc/OracleDS");
con=ds.getConnection("user","pwd"); \\ ("con" is a private Connection instance var)
Then, each of the servlets just use the connection class to connect into the DB.
For instance...
MyConnectionClass con = new MyConnectionClass(); // ("MyConnectionClass" is where the data source info is...)
PreparedStatement ps=con.prepareStatement("SELECT * FROM SOME_TABLE");
ResultSet rs=ps.executeQuery();
more code below...