Connection Pooling and Looking up an EJB through JNDI
While I was reading a tutorial in
EJB today and I read a portion on how a Servlet uses an EJB through JNDI, it
reminded me on how I did connection pooling in Tomcat before in one of my
previous projects.
//Looking up an EJB , from RoseIndia
example by Deepak Kumar
public void init(ServletConfig config) throws ServletException{
//Look up home interface
try {
InitialContext ctx = new InitialContext();
Object objref = ctx.lookup("TestSessionBean");
testSessionBean = (TestSessionBeanHome)PortableRemoteObject.narrow(objref,
TestSessionBeanHome.class);
} catch (Exception NamingException) {
NamingException.printStackTrace();
}
//The way I did Connection pooling
before
public static
Connection getConnectionFromPool()
{
ResourceBundle resourceManager =
ResourceBundle.getBundle(RESOURCE_PROPERTIES);
String dbResource =
resourceManager.getString("dbresource");
Connection conn = null;
try
{
Context ctx = new
InitialContext();
DataSource dataSource
= (DataSource)ctx.lookup("java:comp/env/" + dbResource);
conn =
dataSource.getConnection();
}
catch(NamingException nex)
{
//nex.printStackTrace();
//conn =
DataSourceManager.getConnection();
ConnectionBrokerManager.init();
conn =
ConnectionBrokerManager.getConnection();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
System.out.println("Got Connection:
" + conn.toString() );
return conn;
}
I wasn't able to answer how I
did connection pooling in one of my job interviews before. It amazes me how things
like this is helping me to better understand things now. The name you specify
in ctx.lookup() should be configured in your
container. In tomcat, it's usually in web.xml or context.xml for your
datasource. For EJB's there's ejb-jar.xml and an additional
weblogic-ejb-jar.xml if you're using weblogic.
Additional Resources:
javax.naming.InitialContext
javax.naming.Context