Imagine you have a portlet, and you want to have an EDIT view that displays a form, and on the form you want some precalculated content, such as a dropdown list of available hosts. But how would you do it? You could compute a <select> element and fill it with available hosts by using some Java, but that would clutter up the JSP file. But with a custom tag library you could just do something like:
<mytag:hostlist subnet="192.168.200.0"/>
And that would produce a list of hosts that respond to PING or HTTP or SNMP on the specified subnet. Now how do you do that?
Define a taglib
As in the last post, these are manual instructions. A taglib is just a jar containing at least one .tld file in META-INF. You need a tld file to link the classes in the taglib to their names. Here's an example:
<?xml version="1.0" encoding="ISO-8859-1"?> <taglib xmlns="htp://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>hello</short-name> <description> An example Hello World tag. </description> <tag> <name>hello</name> <tag-class>examples.taglibs.HelloWorldTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
This can go into a directory META-INF inside a directory tld:
- tld
- META-INF
- hello.tld
- META-INF
Now it's time to build the tag class:
package examples.taglibs;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloWorldTag extends TagSupport
{
private static final long serialVersionUID = 1L;
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
try
{
out.println( "<h1>Hello World!</h1>");
}
catch ( IOException ioe )
{
throw new JspException( ioe );
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
This doesn't yet generate a <select> element, but you get the idea how to do it. Compile the java thus:
javac lib/jsp-api.jar tld/src/examples/taglibs/*.java -d tld
which puts HelloWorldTag.class into tld/examples/taglibs,
surprisingly. Then make a jar of the taglib, by cd-ing into the tld directory:
jar cf ../hello.jar META-INF examples
Put your hello.jar taglib into the WEB-INF/lib directory of your web application and you can then call it up from edit.jsp:
<%@ taglib uri="/WEB-INF/lib/hello.jar" prefix="mytag" %>
<html>
<body>
<mytag:hello/>
</body>
</html>
That gives you <h1>Hello world!</h1> in EDIT mode. To get a dropdown list just modify the java code to generate a list and enclose it in <select> tags.
No comments:
Post a Comment