Create and use custom tag libraries to deliver dynamic content to JSPs

You can create custom JSP tags for your Web projects based on the Sun Microsystems JSP 1.2 Specification. Tag libraries are usually created by developers who are proficient in the Java programming language and can be used by Web designers who might not know Java, but would like to enhance their Web site by taking advantage of Java encoded tag libraries.

Implementing custom tags requires all of the following:

  1. Defining custom tags in a Tag Library Descriptor (TLD) file. This is analogous to defining XML tags in a DTD file. The TLD file is an XML file that describes the custom tags in a tag library and includes tag information, such as the tag names, type of content, attributes, and associated tag handler class.

  2. Using custom tags within a JSP page. To use a custom tag within a JSP page, you must first identify where the TLD file is located and identify a prefix to be used when any of the custom tags in the library are included in a JSP page. This is accomplished through the use of a taglib directive.

  3. Creating a Tag Handler class. This is a Java class that implements the Tag or BodyTag interface and is responsible for the implementation of a custom tag at runtime.

A TLD file can be packaged within a JAR file, or as a separately existing project file. If the TLD file is packaged in a JAR file, it must be included under the META-INF folder.

Adding the Tag Library Descriptor (TLD) file

In order to implement custom JSP tags, you must add the Tag Library Descriptor (TLD) file (taglib.tld) to your project.

Add the independent tag library descriptor, taglib.tld to your WEB-INF folder:

  1. In the Project Explorer view of the Web perspective, select the WebContent/WEB-INF folder in your Web project (Chapter1Web).

  2. Right-click the WEB-INF folder and select File > New > Other... > Simple > File. The New File wizard opens.

  3. In the New File dialog enter:

    Enter or select the parent folder - Chapter1Web/WebContent/WEB-INF/tld

    File name - taglib.tld

  4. Click Finish to add your tag library descriptor taglib.tld to your WEB-INF/tld folder.

    Add tag library descriptor

  5. Copy-paste text below into taglib.tld file:

    
    <?xml version="1.0" ?>
    <!DOCTYPE taglib
            PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
    	"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    
    <taglib>
    	<tlib-version>1.0</tlib-version>
    	<jsp-version>1.2</jsp-version>
    	<short-name>hello-utils</short-name>
    	<tag>
    		<name>hello</name>
    		<tag-class>by.iba.rad257.HelloTag</tag-class>
    		<body-content>empty</body-content>
    		<attribute>
    			<name>name</name>
    			<required>true</required>
    			<rtexprvalue>true</rtexprvalue>
    		</attribute>
    	</tag>
    </taglib>
    								
    								

Creating Tag Handler

Create new by.iba.rad257.HelloTag class.

Define the following properties in New Class Dialog:

Source Folder: Chapter1Web/JavaSource

Package: by.iba.rad257

Name: HelloTag

Superclass: TagSupport (use Browse... button)

Creating Tag Handler

Copy-paste in HelloTag.java code shown below:

protected String name = "";

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

public String getName() {
	return name;
}

public int doStartTag() {
	try {
		pageContext.getOut().println("Hello, " + getName());
	} catch (IOException ex) {
	}
	return EVAL_BODY_INCLUDE;
}					
					

Specifying the taglib directive

You need to specify the taglib directive in order to pick up the tags that you are going to put into the document. You can specify taglib directives in one of four ways:

  1. Using the taglib-uri value in the Web deployment descriptor (WEB-INF/web.xml), as follows:

    
    <%@ taglib uri="/yeartags" prefix="year" %>
    <%@ taglib uri="http://www.mycorp/monthtags" prefix="month" %>
    
    								

    where both /yeartags and http://www.mycorp/monthtags are taglib-uri values that are defined in the Web deployment descriptor.

  2. Using the context-relative path that refers directly to the TLD or JAR file, as follows:

    
    <%@ taglib uri="/WEB-INF/tld/datetags.tld" prefix="date" %>
    								
    								

    where /tld/datetags.tld is a context-relative URI to the TLD file.

  3. Using a page-relative path that refers directly to the TLD or JAR file, as follows:

    
    <%@ taglib uri="../WEB-INF/tlds/hourtags.jar" prefix="hour" %>
    								
    								

    where ../WEB-INF/tlds/hourtags.jar is a page-relative URI to the JAR file.

  4. For a J2EE 1.3 Web project only, using the URI element value defined in the TLD, as follows:

    
    <%@ taglib uri="http://www.mycorp/minutetags" prefix="minute" %>
    								
    								

    where http://www.mycorp/minutetags is the URI element value that is defined in the TLD.

    Tip: In a case where two or more TLDs are deployed inside a JAR file, you can use this format to specify each TLD.

Create new JSP file named index.jsp in WebContent folder.

Add the following taglib directive at the top of the page:


<%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix="util" %>
					
					

Add the following custom tag:


<util:hello name="Belarus" />
					
					

Run JSP file on server (note, custom tag output is modified by GreetingFilter web filter):

Custom tag output

Simple Tag Handlers

The API and invocation protocol for classic tag handlers is necessarily somewhat complex because scriptlets and scriptlet expressions in tag bodies can rely on surrounding context defined using scriptlets in the enclosing page.

With the advent of the Expression Language (EL) and JSP Standard Tag Library (JSTL), it is now feasible to develop JSP pages that do not need scriptlets or scriptlet expressions. This allows us to define a tag invocation protocol that is easier to use for many use cases.

In that interest, JSP 2.0 introduces a new type of tag extension called a Simple Tag Extension. Simple Tag Extensions can be written in one of two ways:

Simple Tag Handlers differ from Classic Tag Handlers in that instead of supporting doStartTag() and doEndTag(), the SimpleTag interface provides a simple doTag() method, which is called once and only once for any given tag invocation. All tag logic, iteration, body evaluations, etc. are to be performed in this single method. Thus, simple tag handlers have the equivalent power of BodyTag, but with a much simpler lifecycle and interface.

To support body content, the setJspBody() method is provided. The container invokes the setJspBody() method with a JspFragment object encapsulating the body of the tag. The tag handler implementation can call invoke() on that fragment to evaluate the body as many times as it needs.

A SimpleTag handler must have a public no-args constructor. Most SimpleTag handlers should extend SimpleTagSupport.

Lifecycle:

  1. A new tag handler instance is created each time by the container by calling the provided zero-args constructor. Unlike classic tag handlers, simple tag handlers are NEVER cached and reused by the JSP container.

  2. The setJspContext() and setParent() methods are called by the container. The setParent() method is only called if the element is nested within another tag invocation.

  3. The setters for each attribute defined for this tag are called by the container.

  4. If a body exists, the setJspBody() method is called by the container to set the body of this tag, as a JspFragment. If the action element is empty in the page, this method is not called at all.

  5. The doTag() method is called by the container. All tag logic, iteration, body evaluations, etc. occur in this method.

  6. The doTag() method returns and all variables are synchronized.

BOOT.BY - Tech Industry News         Free SCBCD 1.3 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     Free IBM Certified Associate Developer Study Guide     Free SCJP 5.0 (Tiger) Study Guide     Free Mock Exam Engine     Free SCWCD 1.4 Study Guide     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide     Free SCBCD 5.0 Study Guide