The Wayback Machine - https://web.archive.org/all/20050731231604/http://www.netbeans.org:80/kb/41/tutorial-taglibrary.html

NetBeans IDE 4.1 Tag Library Tutorial

A tag library is a collection of tags used to handle common functions in a JavaServer Pages™ page (JSP™ page), such as formating text, loading graphics, and displaying the current date. A tag can be classified according to its body content in a JSP file:

  • Scriptless tag (default): A tag that has body content containing anything except scripting elements. For example, in this tutorial you create the scriptless FormatTextTag with the style attribute:
       <disp:FormatTextTag style="official">My Company</disp:FormatTextTag>

    This tag uses the syntax for the JavaServer Pages™ technology ("JSP™ syntax") or the Java™ programming language to format the text "My Company".

  • Empty tag: A tag that does not accept body content. For example, in this tutorial you create the empty DisplayLogoTag with the size attribute:
       <disp:DisplayLogoTag size="large"/>

    This tag uses JSP syntax or the Java programming language to display a graphic.

  • Tagdependent tag: A tag that has body content that should not be evaluated, such as SQL statements that are passed to a query tag. This tag is not dealt with in this tutorial.

Because NetBeans IDE 4.1 implements the JavaServer Pages™ 2.0 specification, you can choose to create tag files in JSP syntax or tag handlers in the Java programming language, or both. Tag files do for tag handlers what JavaServer Pages pages do for Java™ servlets: they empower web developers to create complex functionality without being familiar with the Java programming language.

The tag library descriptor (TLD) is an XML document that maps each tag in the library to its associated tag handler or, optionally, to its associated tag file. The TLD describes parameters and scripting variables associated with the tags in the tag library.

Through a taglib directive, a tag library is made available to a page created with the JavaServer Pages™ technology (JSP™ page).

The Tag Library Tutorial shows you how to create your own tag library and use its tags in a web application. However, often you won't need to create your own tags, because many tags have already been created by others. This tutorial shows you how you can incorporate these external tags within your own web application.

The web application that you build in this tutorial shows you how to do the following:

This tutorial can be completed in an hour.


Setting Up A Web Application


Creating a new web application

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.
  2. Under Project Name, type MyCompany.
  3. Set the Project Location to any folder on your computer. From now on, this folder is referred to as $PROJECTHOME. Leave the Set as Main Project checkbox selected. Notice that the Context Path is /MyCompany.
  4. Click Finish. The IDE creates the $PROJECTHOME/MyCompany project folder. The project folder contains all your sources and project metadata, such as the project Ant script. The MyCompany project opens in the IDE. You can view its logical structure in the Projects window and its file structure in the Files window.

Accessing and including graphics

  1. Download the taglib.zip file from http://usersguide.netbeans.org/tutorials/webapps/taglib/taglib.zip.
  2. Unzip the taglib.zip file to your web application's web folder. You can see the new $PROJECTHOME/MyCompany/web/logos folder in the Projects window. The folder contains the LogoLarge.gif file and the LogoSmall.gif file.

Accessing External Tags

Often you do not need to create custom tags yourself. Many custom tags are freely available for use within your web applications.

Accessing tags from the bundled JSTL 1.1 library

Later in this tutorial, you will create tag files that use tags from the JSTL 1.1 library. This library is bundled with NetBeans IDE 4.1. However, you need to add it to your project's classpath.

  1. Right-click the MyCompany project's Libraries node in the Projects window and choose Add Library. Your libraries, as well as those that are bundled with NetBeans IDE 4.1 are displayed. JSTL 1.1 is one of the bundled libraries.
  2. Select JSTL 1.1 and click Add Library.

Accessing tags from the Jakarta project's DateTime Tag Library

Later in this tutorial, you will create a JSP file that uses a tag from the Jakarta project's DateTime Tag Library. This library contains tags that can be used to handle date and time related functions. For example, tags are provided for formatting a date for output, generating a date from HTML form input, using time zones, and localization.

  1. Download the DateTime Tag Library from http://jakarta.apache.org/taglibs/doc/datetime-doc/intro.html.
  2. Right-click the MyCompany project's Libraries node in the Projects window and choose Add JAR/Folder.
  3. Browse and select the taglibs-datetime.jar file.

Creating A Tag Library Descriptor


Creating a TLD file to define the properties of a tag library and its tags

For each tag handler that you create in this tutorial, the NetBeans IDE generates a mapping from the SimpleTagLib TLD file to the tag's implementation in the tag handler's Java class.

  1. Right-click the MyCompany project node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Tag Library Descriptor and click Next.
  2. Type SimpleTagLib in the Tag Library Descriptor File Name Name text box.
  3. Type http://netbeans.org/tlds/SimpleTagLib in the URI text box.
  4. Click Finish. The IDE creates the web/WEB-INF/tlds folder and adds the tag library descriptor to it. SimpleTagLib.tld opens in the Source Editor.

Creating An Empty Tag to Display Graphics

You don't need to know the Java programming language to create tags. If you are more comfortable with JSP syntax, use Scenario 1 to create a tag file. Otherwise, use Scenario 2 to create a tag handler in the Java programming language.

Scenario 1: JSP syntax

  1. Right-click the MyCompany project node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Tag File and click Next.
  2. Type DisplayLogoTag in the Tag File Name text box. Note that the IDE adds the tag file to the WEB-INF/tags folder. Click Finish. DisplayLogoTag.tag opens in the Source Editor.
  3. Replace the default code with the following:
    
       <%@tag description = "Display logo" pageEncoding="UTF-8"%>
       <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
       <%@attribute name="size" required="true"%>
    
           <c:choose>
    	   <c:when test="${size == 'large'}">
    	       <img
    		src='logos/LogoLarge.gif'
                    align='Center'>
    	   </c:when>
    	   <c:otherwise>
                   <img
                    src='logos/LogoSmall.gif'
                    align='Center'>
               </c:otherwise>
           </c:choose>
    
       <jsp:doBody/>
    
    

    Note: The tag file includes a <%@taglib> directive with a uri attribute, which specifies that the prefix c refers to a tag handler in the JSTL 1.1 library. See the Use Tags section below for further details on this directive. To be able to use the JSTL 1.1 library, you must add it to your web application as described in the Accessing tags from the bundled JSTL 1.1 library section above.

  4. Press Ctrl-Shift-F to format the file.
  5. Press Ctrl-S to save the file.

Scenario 2: Java programming language

  1. Right-click the MyCompany project node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Tag Handler and click Next.
  2. Type DisplayLogoTag in the Class Name text box and type org.me.logo in the Package combo box. Note that the IDE adds the tag handler to the Source Packages folder. Make sure that SimpleTagSupport is selected and click Next.
  3. Click Browse and select your SimpleTagLib tag library descriptor in the WEB-INF/tlds folder.
  4. Select Empty under Body Content.
  5. Click New. Type size in the Attribute Name text box and select the Required Attribute checkbox. Click OK.
  6. Click Finish. DisplayLogoTag.java opens in the Source Editor.
  7. Select doTag from the dropdown above the Source Editor. The cursor is set on the doTag method.
  8. Modify the doTag method by replacing the first // TODO section with the following code:
    
          if (size.equals("large"))
          	out.println("<img src='logos/LogoLarge.gif' align='Center' />");
          else
    	out.println("<img src='logos/LogoSmall.gif' align='Center' />");
    
    
  9. Press Ctrl-Shift-F to format the file.
  10. Press Ctrl-S to save the file.

Creating A Scriptless Tag to Format Text

You don't need to know the Java programming language to create tags. If you are more comfortable with JSP syntax, use Scenario 1 to create a tag file. Otherwise, use Scenario 2 to create a tag handler in the Java programming language.

Scenario 1: JSP syntax

  1. Right-click the MyCompany project node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Tag File and click Next.
  2. Type FormatTextTag in the Tag File Name text box. Note that the IDE adds the tag file to the WEB-INF/tags folder. Click Finish. FormatTextTag.tag opens in the Source Editor.
  3. Replace the default code with the following:
    
       <%@tag description = "Format text" pageEncoding="UTF-8"%>
       <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
       <%@attribute name="style" required="true"%>
    
          <c:choose>
    	   <c:when test="${style == 'official'}">
    	       <b><i><font size='+3' color='red'>
    	   </c:when>
    	   <c:otherwise><font size='+1'></c:otherwise>
           </c:choose>
    
       <jsp:doBody/>
    
           <c:choose>
    	   <c:when test="${style == 'official'}">
    	       </font></i></b>
    	   </c:when>
    	   <c:otherwise></font></c:otherwise>
           </c:choose>
    
    

    Note: The tag file includes a <%@taglib> directive with a uri attribute, which specifies that the prefix c refers to a tag handler in the JSTL 1.1 library. See the Use Tags section below for further details on this directive. To be able to use the JSTL 1.1 library, you must add it to your web application as described in the Accessing tags from the bundled JSTL 1.1 library section above.

  4. Press Ctrl-Shift-F to format the file.
  5. Press Ctrl-S to save the file.

Scenario 2: Java programming language

  1. Right-click the MyCompany project node and choose New > File/Folder. Under Categories, select Web. Under File Types, select Tag Handler and click Next.
  2. Type FormatTextTag in the Class Name text box. Note that the IDE adds the tag handler to the org.me.logo package within the Source Packages folder. Make sure that SimpleTagSupport is selected and click Next.
  3. Click Browse and select your SimpleTagLib tag library descriptor in the WEB-INF/tlds folder.
  4. Make sure that Scriptless is selected under Body Content.
  5. Click New. Type style in the Attribute Name text box and select the Required Attribute checkbox. Click OK.
  6. Click Finish. FormatTextTag.java opens in the Source Editor.
  7. Select doTag from the dropdown above the Source Editor. The cursor is set on the doTag method.
  8. Modify the doTag method as follows:

    • Replace the first // TODO section with the following:
      
            if (style.equals("official"))
            	out.println("<b><i><font size='+3' color='red'>");
            else
               out.println("<font size='+1'> ");
      
      
    • Replace the second // TODO section with the following:
      
            if (style.equals("official"))
      	out.println("</font></i></b>");
            else
      	out.println("</font>");
      
      
  9. Press Ctrl-Shift-F to format the file.
  10. Press Ctrl-S to save the file.

Using Tags in a JSP File


Scenario 1: Referencing tag files (JSP syntax)

  1. In the Projects window, expand the MyCompany project node and the Web Pages node. Notice the IDE has created a default JavaServer Pages page, index.jsp, for you.
  2. Double-click index.jsp. It opens in the Source Editor.
  3. In the Source Editor, create a taglib directive as follows:
    • Insert a line under the last <%@page> directive, and type <%@taglib. The code completion box should open and display <%@taglib>. Press Enter. If the code completion box does not appear, press Ctrl-Space.
    • Press the Space bar. The code completion box opens and displays all the attributes for the taglib directive. If the code completion box does not open, press Ctrl-Space to manually open it.
    • Use the arrow keys to select prefix in the code completion box and press Enter.
    • Press the Space bar again and select tagdir and Press Enter.
    • Type disp between the quotation marks for the prefix.
    • Place the cursor between the quotation marks for the tagdir and press Ctrl-Space. The code completion box should open and display all the web application's tag libraries.
    • Use the arrow keys to select /WEB-INF/tags and press Enter. The taglib directive should look like the following line:
          <%@taglib prefix="disp" tagdir="/WEB-INF/tags" %>
  4. Now reference the Jakarta project's tag handlers and use the tags in a JSP file.

Scenario 2: Referencing tag handlers (Java programming language)

  1. In the Projects window, expand the MyCompany project node and the Web Pages node. Notice the IDE has created a default JavaServer Pages page, index.jsp, for you.
  2. Double-click index.jsp. It opens in the Source Editor.
  3. In the Source Editor, create a taglib directive as follows:
    • Insert a line under the last <%@page> directive, and type <%@taglib. The code completion box opens and displays <%@taglib>. Press Enter. If the code completion box does not appear, press Ctrl-Space to manually open it.
    • Press the Space bar. The code completion box opens and displays all the attributes for the taglib directive. If the code completion box does not open, press Ctrl-Space to manually open it.
    • Use the arrow keys to select prefix in the code completion box and press Enter.
    • Press the Space bar again and select uri and press Enter.
    • Type disp between the quotation marks for the prefix.
    • Place the cursor between the quotation marks for the uri and press Ctrl-Space. The code completion box opens and displays all the web application's tag libraries.
    • Use the arrow keys to select http://netbeans.org/tlds/SimpleTagLib and press Enter. The taglib directive should look like the following line:
          <%@taglib prefix="disp" uri="http://netbeans.org/tlds/SimpleTagLib" %>

Both scenarios: Referencing the Jakarta project's tag handlers through the DateTime-1.0 TLD file

  • Add a taglib directive to reference the Jakarta project's DateTime TLD file:
        <%@taglib prefix="dt" uri="http://jakarta.apache.org/taglibs/datetime-1.0" %>

Both scenarios: Using tags in a JSP file

  1. Replace the <body> tags and their content with the following code:
    
       <body>
          <disp:DisplayLogoTag size="large"/>
          <disp:FormatTextTag style="official">My Company</disp:FormatTextTag>
    
          <p><blockquote>This is <disp:FormatTextTag style="professional">My Company</disp:FormatTextTag>.
          It's a fun company and we make extremely useful products.</blockquote>
    
          <p align="center"><disp:DisplayLogoTag size="small"/>
          My Company<br>
          1234 Any St.<br>
          Anytown, CA 95110
    
          <br><br>
          Today's date: <b><dt:format pattern="MM/dd/yyyy"><dt:currentTime/></dt:format></b>
    
       </body>
    
    
  2. Press Ctrl-Shift-F to format the file.
  3. Press Ctrl-S to save the file.

Compiling and Executing A Web Application


Building a project

  • Choose Build > Build Main Project (F11). The MyCompany project is built.

Running a project

  1. Choose Run > Run Main Project (F6) from the Run menu. Double-click the Output window's titlebar to maximize it so you can see all the output. Note that Ant builds MyCompany.war first and then compiles the project using it. Finally, it deploys the web application using the IDE's default server as shown below:

    Web browser after MyCompany application is executed.

  2. Double-click the Output window's titlebar to return it to its normal size. Select the Files window and expand the project node. The build class files are in the build folder. The build WAR file (MyCompany.war) is in the dist folder.

Generating Javadoc

  • In the Projects window, right-click the project node and choose Generate Javadoc for Project. Javadoc output appears in the Output window, and your web browser opens displaying the Javadoc.

Troubleshooting

You can only use the following two troubleshooting strategies if you chose the Java route (Scenario 2) to create tag handlers.

Validating that your tags use the prescribed body content

The SimpleTagLib TLD file created in this tutorial maps tags in the library to an associated tag handler. When you compile the index.jsp file, the NetBeans IDE identifies conflicts between the mappings and the way their corresponding tags have been used in the JSP file. To illustrate this, do the following:

  1. Expand the MyCompany project node, expand the Web Pages node, expand the WEB-INF node, and expand the tlds node. Double-click the SimpleTagLib.tld node. The tag library descriptor opens in the Source Editor.
  2. Change the value of the FormatTextTag's <bodycontent> tag from scriptless to empty.
  3. Double-click the index.jsp file. It opens in the Source Editor. Note that the FormatTextTag is not empty. For example, its first instance is as follows:
        <disp:FormatTextTag style="official">My Company</disp:FormatTextTag>
    Compare this to the instances of the DisplayLogoTag, which are empty in the index.jsp file:
        <disp:DisplayLogoTag size="large"/>
        <disp:DisplayLogoTag size="small"/>
  4. Make sure that your JSP file's <%@taglib> directive points to the SimpleTagLib.tld tag library descriptor. The <%@taglib> directive should look like the following line:
        <%@taglib prefix="disp" uri="http://netbeans.org/tlds/SimpleTagLib" %>
  5. Right-click index.jsp and choose Compile File (F9) from the contextual menu. The JSP file does not compile because of the following error:
        org.apache.jasper.JasperException:  According to TLD, tag disp:FormatTextTag
        must be empty, but is not
  6. In the the SimpleTagLib.tld file, change the value of the FormatTextTag's <bodycontent> tag from empty back to scriptless.
  7. Right-click index.jsp and choose Compile File (F9) from the contextual menu again. The JSP file is compiled.

Validating that your tags use the prescribed tag libraries

The PermittedTaglibsTLV validator is part of the JSTL 1.1 library. It allows a TLD to restrict which tag libraries, in addition to itself, may be imported in a JSP file.

Note: You must specify a permitted tag library's URI in the <param-value> section. A tag handler has a URI property, a tag file does not. Therefore, the PermittedTaglibs validator is currently only supported for tag handlers.

  1. Right-click the MyCompany project node and choose New > Tag Library Descriptor.
  2. Type ApprovedTagLibs in the Class Name text box.
  3. Type http://netbeans.org/tlds/ApprovedTagLibs in the URI text box.
  4. Click Finish. The IDE adds the tag library descriptor to it. ApprovedTagLibs.tld opens in the Source Editor.
  5. In the Source Editor, replace the default <validator> tags with the following code:
  6. 
       <validator>
          <validator-class>
            javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV
          </validator-class>
          <init-param>
               <param-name>permittedTaglibs</param-name>
    	   <param-value>
    	       http://jakarta.apache.org/taglibs/datetime-1.0
               </param-value>
          </init-param>
       </validator>
    
    
  7. Add a taglib directive to the index.jsp file to reference the ApprovedTagLibs TLD file:
        <%@taglib prefix="apptglib" uri="http://netbeans.org/tlds/ApprovedTagLibs" %>
  8. Right-click index.jsp and choose Compile File (F9) from the contextual menu. The JSP file does not compile because of the following error:
        org.apache.jasper.JasperException: <h3>Validation error messages from TagLibraryValidator
        for accepted-taglibs<p>null: taglib apptglib (urn:jsptld:/WEB-INF/tlds/accepted-taglibs)
        allows only the following taglibs to be imported: [http://jakarta.apache.org/taglibs/datetime-1.0]</p>
  9. In the the ApprovedTagLibs.tld file, add the http://netbeans.org/tlds/SimpleTagLib line to the <param-value> section. The validator now looks as follows:
    
       <validator>
          <validator-class>
            javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV
          </validator-class>
          <init-param>
               <param-name>permittedTaglibs</param-name>
    	   <param-value>
    	       http://jakarta.apache.org/taglibs/datetime-1.0
                   http://netbeans.org/tlds/SimpleTagLib
               </param-value>
          </init-param>
       </validator>
    
    
  10. Right-click index.jsp and choose Compile File (F9) from the contextual menu again. The JSP file is compiled.

Next Steps

For more information about using NetBeans IDE 4.1, see the following resources:

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE J2EE development features, join the mailing list .