caucho
Resin
FAQ
Reference Guide
Demo
Tutorial

JSP page
Config
URLs
Database Forms
XTP Copy
Hello Tag
Vary Filter
HardCore
Mailing Forms
Beans
Cache
XSL Filter
run-at

Attr Tag
Mail Tag
XSL Tag
Connection Tag
 Connection Tag

XSL Tag
Hello Tag
Vary Filter

The connection tag provides a robust way for a JSP page to get a database connection without getting tangled up in the APIs to make that work.

The JSP 1.2 TryCatchFinally interface lets tag library designers create more robust libraries. For example, database connections must always be closed, even when exceptions occur. The TryCatchFinally interface lets a ConnectionTag automatically close the connection when the tag completes.

The connection tag example creates a JSP tag to look up a database data source in the environment using JNDI. From that data source, it creates a new connection and makes it available to the page. When the connection tag completes, it automatically closes the connection.

Using the connection tag
houses.jsp
<%@ page import="java.sql.*" %>
<%@ taglib prefix="ct" uri="/WEB-INF/conn.tld" %>
<h1>House Scores</h1>

<ct:connection name="jdbc/hogwarts">
<%
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("select NAME, POINTS from HOUSES");

while (rs.next()) {
  %><%= rs.getString(1) %> <%= rs.getInt(2) %><br><%
}
rs.close();
stmt.close();
%>
</ct:connection>

<h1>House Scores:</h1>

griffindor 482<br>
ravenclaw 426<br>
hufflepuff 352<br>
slytherin 472<br>

<%@ taglib prefix="ct" ... %>

The taglib declaration configures ct as a tag prefix. Following tags with the prefix ct, like ct:connection map to JSP tag implementations, in this case to instances of ConnectionTag.

The taglib uri, WEB-INF/conn.tld, specifies the tag library descriptor file. The tld tells Resin maps tag names to tag classes and specifies tag attributes.

<ct:connection name="jdbc/hogwarts">

  • Looks up the DataSource in JNDI.
  • Creates a new Connection
  • Creates a variable, conn, holding the connection.
  • Automatically closes the connection at tag close.

</ct:connection>

When the ct:connection tag closes, the tag closes the connection. By using the TryCatchFinally interface, the tag can guarantee it will close the connection with an exception.

Implementation of the Connection Tag
ConnectionTag.java
package test;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

import javax.naming.*;
import javax.sql.*;

public class ConnectionTag extends TagSupport implements TryCatchFinally {
  private Connection conn;

  // JNDI name of the connection
  private String name;

  public void setName(String name)
  {
    this.name = name;
  }

  public int doStartTag()
    throws ServletException
  {
    try {
      Context env = (Context) new InitialContext().lookup("java:comp/env");

      DataSource ds = (DataSource) env.lookup(name);

      if (ds != null)
        conn = ds.getConnection();
    } catch (Exception e) {
      throw new ServletException(e);
    }

    if (conn == null)
      throw new ServletException("can't open connection " + name);

    pageContext.setAttribute("conn", conn);
    
    return EVAL_BODY_INCLUDE;
  }
  
  public void doCatch(Throwable t)
    throws Throwable
  {
    throw t;
  }

  public void doFinally()
  {
    try {
      Connection conn = this.conn;
      this.conn = null;
      pageContext.removeAttribute("conn");

      conn.close();
    } catch (Exception e) {
    }
  }
}

implements TryCatchFinally

The new TryCatchFinally interface of JSP 1.2 lets tags handle exceptions gracefully. The ConnectionTag uses the doFinally() method of TryCatchFinally close the connection even when an exception occurs.

setName(name)

Attributes in JSP tags use Bean methods to set values. When Resin evaluates the ct:connection tag, it will call setName with the name value. In this example, it will call setName("jdbc/hogwarts").

The database name, jdbc/hogwarts, matches its configuration in the resin.conf or web.xml as described in the database config page.

doStartTag()

Resin calls ConnectionTag's doStartTag method after setting the attributes. Typically a passthrough tag like ConnectionTag will return EVAL_BODY_INCLUDE so JSP will interpret the contents as normal JSP.

new InitialContext()

The database is stored using JNDI, the Java Naming and Directory Interface. The lookup() method used in this example is sufficient for 90% of projects.

JNDI provides a global singleton, InitialContext, and namespace, letting applications grab configuration information from any class. JNDI is nice since you don't need to pass around a configuration variable. You can just use InitialContext where you need it.

In the example, the database source is stored in java:comp/env/jdbc/hogwarts. The database form example uses the same JNDI pattern to grab its database.

ds.getConnection()

With Java's database interface, JDBC, applications grab connections from a data source. With Resin, the data source automatically pools database connections.

pageContext.setAttribute

ct:connection creates a new Java variable, conn. ConnectionTag passes the connection to the JSP page by setting the conn attribute in the pageContext. pageContext is a protected variable inherited from the TagSupport class and set by the JSP page before calling any other methods.

doFinally()

Applications must always close connection objects. Failing to close the connection will give the connection pool fits. By using the TryCatchFinally interface and implementing doFinally(), ConnectionTag can make sure the connection is always closed even when exceptions happen.

Declaring Variables

Because the ct:connection tag creates new variables in the JSP page, the tag library needs to create a tag info class to declare the variables.

The tag info class returns an array of all the variables. This example has a single variable, conn, which has the type java.sql.Connection. The variable is only valid inside the tag, so its scope is VariableInfo.NESTED.

Tag Info
package test;

import javax.servlet.jsp.tagext.*;

public class ConnectionTagInfo extends TagExtraInfo  {
  public VariableInfo []getVariableInfo(TagData data)
  {
    VariableInfo []info = new VariableInfo[1];
    info[0] = new VariableInfo("conn", "java.sql.Connection",
                               true, VariableInfo.NESTED);

    return info;
  }
}

Taglib Configuration

The tag library descriptor (tld) associates the tag name, connection, with the tag class test.ConnectionTag and the tag info class test.ConnectionTagInfo.

The tag has a single attribute, name, which is required.

WEB-INF/conn.tld
<taglib>
  <tag>
    <name>connection</name>
    <tagclass>test.ConnectionTag</tagclass>
    <teiclass>test.ConnectionTagInfo</teiclass>
    <attribute>
      <name>name</name>
      <required>true</required>
    </attribute>
  </tag>
</taglib>

Database Configuration

The database configuration example more fully describes the database configuration.

resin.conf
<caucho.com>

<resource-ref>
  <res-ref-name>jdbc/hogwarts</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <init-param driver-name="org.gjt.mm.mysql.Driver"/>
  <init-param url="jdbc:mysql://localhost:3306/test_hogwarts"/>
  <init-param user="ferg"/>
  <init-param password="changeit"/>
</resource-ref>

<http-server>
  ...
</http-server>

</caucho.com>

resource-ref

A resource-ref describes a factory resource. When Resin initializes, it will create the factory and store it in the JNDI context.

res-ref-name

res-ref-name gives the JNDI name. The value of res-ref-name is appended to java:comp/env. So this example will produce the full JNDI name of java:comp/env/jdbc/hogwarts.

res-type

res-type describes the type of the resource. This example is a JDBC data source, so it uses the name javax.sql.DataSource. An applications could replace res-type with an arbitrary bean names; Resin would instantiate, initialize and bind the bean to the JNDI context.

init-param

init-param uses Bean introspection to initialize the new resource. The parameter name is converted to a method name. For example, driver-name maps to setDriverName and url maps to setURL. After creating the new resource, Resin will call all the initializers to configure it.


XSL Tag
Hello Tag
Vary Filter
Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark, and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc.