Declaration of a reference to a JDBC connection factory that returns objects of type javax.sql.DataSource:
<resource-ref> <description> Primary database </description> <res-ref-name> jdbc/primaryDB </res-ref-name> <res-type> javax.sql.DataSource </res-type> <res-auth> Container </res-auth> </resource-ref>
<res-type> is a fully-qualified class name of the resource factory. The <res-auth> variable can be assigned either Container or Application as a value.
If Container is specified, the web container handles the authentication before binding the resource factory to JNDI lookup registry. If Application is specified, the servlet must handle authentication programmatically. Different resource factories are looked up under a separate sub-context that describes the resource type, follows:
jdbc/ for a JDBC javax.sql.DataSource factory
mail/ for a JavaMail javax.mail.Session factory
url/ for a java.net.URL factory
Here is a code snippet to get JDBC connection from an application component with the container handling the authentication:
InitialContext initContext = new InitialContext(); DataSource source = (DataSource) initContext.lookup("java:comp/env/jdbc/primaryDB"); Connection conn = source.getConnection();
Please note that in order to ensure that for these resource references work, the res-ref-name must map to valid resource factory at runtime.
Resource environment references provide a way of accessing, by using JNDI lookups, administered objects associated with a resource. The <resource-env-ref> element, defined in the standard deployment descriptors lets applications declare the resource requirements.
The main difference between <resource-env-ref> and <resource-ref> element is the absence of specific resource authentication requirement, both these elements have to be backed up by a resource factory descriptor.