20 November 2008

Dependency Injection in Taglibs

Helping with some migration material recently for OC4J --> WLS, a question was asked about whether OC4J 10.1.3.x supported dependency injection with its Tag library implementation.

It's known that OC4J supports dependency injection in the Web container as described here, but the specifics of whether that extended to tag librarieswas not mentioned.

A subsequent quick test verified that dependency injection does indeed work for tags using the  SimpleTag (SimpleTagSupport) and BodyTag (BodyTagSupport).
package sab.testdi.tag;

import java.io.*;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import sab.testdi.ejb.CalcLocal;

public class CalcAdd extends SimpleTagSupport {

CalcLocal calc;

int v1 = 0;
int v2 = 0;

public void setV1(int v1) {
this.v1 = v1;

public void setV2(int v2) {
this.v2 = v2;

public void doTag() throws JspException, IOException {
PrintWriter out = new PrintWriter(this.getJspContext().getOut());
out.printf("<div style='font-family: courier'>");
if(calc != null) {
out.printf("%s+%s=%s", v1, v2, calc.add(v1, v2));
} else {
out.printf("bugger, calc is null!");

The taglib.tld file defines the tag:
<?xml version = '1.0' encoding = 'windows-1252'?>
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<description>A short description...</description>
<example><calc:add v1="100" v2="25"/></example>
And finally, a JSP can use it by importing the JAR file containing the tag libraru into the WEB-INF/lib directory (where it is nicely auto-discovered) and making a call to the <calc:add .../> tag.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="/webapp/calc" prefix="calc"%>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<body style="font-family: arial">
<h2>Testing Taglib Dependency Injection</h2>
<calc:add v1="12" v2="12"/></p>

When the JSP is accessed it successfully displays 12+12=24 which is rendered by the tag library after being calculated via the injected EJB reference.

No comments: