How to use Simple Tag Handlers in J2EE


In J2EE environment tag files use another JSP files for implementing the functionality of tags however tag handlers use Java classes. So that, it is more flexible to use tag handlers if you need to design your own tags in a J2EE Project.

In this post, I am going to explain How to code a Simple Tag Handler with three basic examples including;

  • Simple tag handler without a body
  • Simple tag handler with a body
  • Simple tag with an attribute

First of all, you will need to put the following tld files inside a folder tlds inside WEB-INF folder.

WEB-INF>tlds
–>dateFinderSimpleTags.tld
–>iteratorSimpleTags.tld
–>specificWordReplacerSimpleTags.tld

The content for these files are like below;

dateFinderSimpleTags.tld

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<taglib xmlns=”http://java.sun.com/xml/ns/javaee&#8221;
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
    xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&#8221;
    version=”2.1″>
<tlib-version>1.0</tlib-version>

    <!– tag lib directive inside a jsp file will use the following name example –>  
    <!– <%@taglib prefix=”customTags” uri=”simpleTagsDateTime”%>–>
    <uri>simpleTagsDateTime</uri>
    <tag>
<description>This tag handler is used for getting server time</description>
        <!–custom tag will use the following name for mapping example <customTags:findDatetime/>–>
        <name>findDateTime</name>
        <tag-class>com.tunatore.simpletaghandlerexample.SimpleTagHandlerDateFinder</tag-class>
        <!– body content for the tag is NOT allowed –>
        <body-content>empty</body-content>
</tag>

</taglib>

iteratorSimpleTags.tld

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<taglib xmlns=”http://java.sun.com/xml/ns/javaee&#8221;
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
    xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&#8221;
    version=”2.1″>
<tlib-version>1.0</tlib-version>

    <!– tag lib directive inside a jsp file will use the following name example –>  
    <!– <%@taglib prefix=”customTags” uri=”simpleTagsWithIterator”%>–>
    <uri>simpleTagsWithIterator</uri>
    <tag>
        <description>This tag handler is used for replacing a specific word inside a tag body</description>
        <!–custom tag will use the following name for mapping example <customTags:peopleIterator/>–>
        <name>peopleIterator</name>
        <tag-class>com.tunatore.simpletaghandlerexample.SimpleTagHandlerPeopleIterator</tag-class>
        <!– body content for the tag is allowed –>
        <body-content>scriptless</body-content>    
        <!– define an atrribute for the tag like below–>
        <attribute>
            <name>peopleList</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

specificWordReplacerSimpleTags.tld

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<taglib xmlns=”http://java.sun.com/xml/ns/javaee&#8221;
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
    xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&#8221;
    version=”2.1″>
<tlib-version>1.0</tlib-version>

    <!– tag lib directive inside a jsp file will use the following name example –>  
    <!– <%@taglib prefix=”customTags” uri=”simpleTags”%>–>
    <uri>simpleTagsWordReplacer</uri>
    <tag>
        <description>This tag handler is used for replacing a specific word inside a tag body</description>
        <!–custom tag will use the following name for mapping example <customTags:wordReplacer/>–>
        <name>wordReplacer</name>
<tag-class>com.tunatore.simpletaghandlerexample.SimpleTagHandlerSpecificWordReplacer</tag-class>
        <!– body content for the tag is allowed –>
        <body-content>scriptless</body-content>
</tag>

</taglib>

Next you need to create Java Classes for these Simple Tag Handlers such as the following ones;

SimpleTagHandlerDateFinder .java

package com.tunatore.simpletaghandlerexample;

import java.io.IOException;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author tunatore
 */
public class SimpleTagHandlerDateFinder extends SimpleTagSupport{

    @Override
    public void doTag() throws JspException, IOException {       
        //will write the content inside a jsp file
        getJspContext().getOut().print(Calendar.getInstance().getTime().toString());        
    }       
}

SimpleTagHandlerPeopleIterator.java
package com.tunatore.simpletaghandlerexample;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author tunatore
 */
public class SimpleTagHandlerPeopleIterator extends SimpleTagSupport{

    private List peopleList;

    @Override
    public void doTag() throws JspException, IOException {    

        People people1 = new People(“James”,”Gosling”);
        People people2 = new People(“Bill”,”Gates”);
        People people3 = new People(“Tuna”,”Tore”);

        peopleList = new ArrayList();
        peopleList.add(people1);     
        peopleList.add(people2);
        peopleList.add(people3);

        for (Iterator it = peopleList.iterator(); it.hasNext();) {
            People people = (People)it.next();
            getJspContext().setAttribute(“people”, people);
            //null says that the tag handler write its content inside the tag
            //not for another writer
            getJspBody().invoke(null);
        }

    }

    /**
     * @return the peopleList
     */
    public List getPeopleList() {
        return peopleList;
    }

    /**
     * @param peopleList the peopleList to set
     */
    public void setPeopleList(List peopleList) {
        this.peopleList = peopleList;
    }

}

SimpleTagHandlerSpecificWordReplacer.java
package com.tunatore.simpletaghandlerexample;

import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author tunatore
 */
public class SimpleTagHandlerSpecificWordReplacer extends SimpleTagSupport{

    @Override
    public void doTag() throws JspException, IOException {    

       StringWriter stringWriter = new StringWriter();
       getJspBody().invoke(stringWriter);
       getJspContext().getOut().print(“Original Text</br>”);
       getJspContext().getOut().print(“</br>##################</br>”);
       getJspContext().getOut().print(stringWriter);
       String replacedContent = stringWriter.getBuffer().toString().replaceAll(“C#”,”Java”);      
       //this will write the content
       getJspContext().getOut().print(“</br>##################</br>”);
       getJspContext().getOut().print(“</br>Replaced Text</br>”);
       getJspContext().getOut().print(“</br>##################</br>”);
       getJspContext().getOut().print(replacedContent);
       getJspContext().getOut().print(“</br>##################</br>”);
    }       
}

And last for the classes create a People class as bean inside the same package

People.java

package com.tunatore.simpletaghandlerexample;

/**
 *
 * @author tunatore
 */
public class People {

    private String name;
    private String surname;

    People(String name, String surname) {    
        this.name = name;
        this.surname = surname;    
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the surname
     */
    public String getSurname() {
        return surname;
    }

    /**
     * @param surname the surname to set
     */
    public void setSurname(String surname) {
        this.surname = surname;
    }        

}

For testing custom tags I created 3 basic jsp files such as the following ones;

simpleTagWithIterator.jsp

<%–
    Document   : index
    Created on : 03.June.2011, 16:39:20
    Author     : tunatore
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”customTags” uri=”simpleTagsWithIterator”%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
         <title>Simple Tag Handler Body Itetor (People Iterator) Example</title>
    </head>
    <body style=”background-color:lightsteelblue” >
        <h1>People Iterator Example</h1>
        <table border=”1″ width=”400px”>
            <tr><th><b>Name</b></th><th><b>Surname</b></th></tr>
            <customTags:peopleIterator peopleList=”${peopleList}”>
                <tr><td>${people.name}</td><td>${people.surname}</td></tr>
            </customTags:peopleIterator>
        </table>
    </body>
</html>

simpleTagWithaBody.jsp

<%–
    Document   : index
    Created on : 03.June.2011, 16:39:20
    Author     : tunatore
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”customTags” uri=”simpleTagsWordReplacer”%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>Simple Tag Handler With a Body Example</title>
    </head>
    <body style=”background-color:lightsteelblue” >
        <h1>Word Replacer example</h1>
        <b>
          <customTags:wordReplacer>
              We all like C# developers because they are open source advocates!
              C# developers are perfect!
          </customTags:wordReplacer>
        </b>
    </body>
</html>

simpleTagWithoutBody.jsp

<%–
    Document   : index
    Created on : 03.June.2011, 16:39:20
    Author     : tunatore
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”customTags” uri=”simpleTagsDateTime”%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
         <title>Simple Tag Handler With a Body Example</title>
    </head>
    <body style=”background-color:lightskyblue” >
        <h1>Get Server Time</h1>
        <b><customTags:findDateTime/></b>
    </body>
</html>

After calling these jsp files results will be same as the following screens;

If you run simpleTagWithoutBody.jsp you will get the following result

If you run simpleTagWithaBody.jsp you will get the following result


If you run simpleTagWithIterator.jsp you will get the following result


Download Project

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s