Search code examples
javajakarta-eejdbcjndi

What is the java "Context" class used for?


I'm checking a java webpage code, actually a Liferay portlet's based website.

I was checking the server-side .java files, and in a DAO pattern file, seeing how the programmer dealt with the DB connections. I'm used to Java SE, where you normally get a Connection object calling to the DriverManager class, but here, things are pretty different:

initContext = new InitialContext();
envContext = (Context) initContext.lookup("java:/comp/env");
ds = (DataSource) envContext.lookup("jdbc/SSMoracle");
conn = ds.getConnection();  

Doing this, the object conn gets a proper connection to the DB, and it works perfectly. I've never seen how it works though, especially the Context class.

What does this class do, and why is it used instead of using a class that calls DriverManager to get the proper connection? I would love to know!


Solution

  • It is part of JNDI, the Java Naming and Directory Interface. This is one of the services that a Java EE container offers.

    Applications can lookup things like data sources (for database access) in JNDI. An administrator can define and configure a data source in the administration console of the Java EE container.

    The lines of code that you have in your question do exactly that: lookup a DataSource through JNDI, and then get a database connection from the DataSource.

    Have a look at, for example, the documentation of Apache Tomcat to see how this works when you would use the Tomcat servlet container: JNDI Resources HOW-TO and JNDI Datasource HOW-TO