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 10.1.3.1+ 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 {

@EJB(name="Calc")
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!");
}
out.println("</div>");
}
}

The taglib.tld file defines the tag:
<?xml version = '1.0' encoding = 'windows-1252'?>
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee">
<display-name>calc</display-name>
<tlib-version>1.2</tlib-version>
<short-name>calc</short-name>
<uri>/webapp/calc</uri>
<tag>
<description>A short description...</description>
<display-name>add</display-name>
<name>add</name>
<tag-class>sab.testdi.tag.CalcAdd</tag-class>
<body-content>empty</body-content>
<attribute>
<name>v1</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>v2</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<example><calc:add v1="100" v2="25"/></example>
</tag>
</taglib>
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"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="/webapp/calc" prefix="calc"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>Index</title>
</head>
<body style="font-family: arial">
<h2>Testing Taglib Dependency Injection</h2>
<p>
<calc:add v1="12" v2="12"/></p>
</body>
</html>

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: