Thursday, April 28, 2011

Chapter 44: JSP Tag Libraries

In the previous few chapters, we saw how JavaBeans help us encapsulate functionality in classes inside a JSP Page using XML notations (tags). Although the reference to such a JavaBean allows you to access attributes and methods via scriptlets, the XML notation itself is limited to getting and setting properties in the JavaBean. Once you have the reference, as mentioned, you can treat the JavaBean like any object in scriptlets by calling its methods and getting/setting its properties. However, in many cases, you may prefer to use an XML-based syntax for invoking these methods rather than having to invoke them via a scriptlet.

The answer to this requirement is the JSP Tag Library. In this chapter, and the next one, we are going to find out in detail about these tag libraries or taglibs as they are frequently called.

So, lets get started!!!

What is a Tag Library?

A tag library is similar to JavaBeans, which means that you can reference a class from JSP using XML notation. However, unlike JavaBeans, tag libraries have a specific lifecycle protocol. So, whenever you use a tag library tag, the container calls the lifecycle event methods in your tag handler (doStart, doStartTag, doAfterBody). Typically, you use these methods to return a string, which the container places inline where the tag is located in the JSP page.

A tag library maps XML tags to underlying class methods in a Tag Library Descriptor (.tld) file. This file defines the custom tags that you can use in JSP to access the associated Java class. Your container (in this case, Tomcat) uses the TLD to convert the XML in your JSP page into Java code. TLD files are written in XML notation.

Let us take a look at how we can define a custom tag for use.

< tag >
< name > guessColors < / name >
< tagclass > examples.MyColorHandlerTag < / tagclass >
< info > Simply prints some text < / info >
< attribute >
< name > color < / name >
< required > true < / required >
< rtexprvalue > false < / rtexprvalue >
< / attribute >
< / tag >

This is how you create a custom tag and this tag can be used in your JSP page, provided it is described in the tag library or the .tld file.

Why use Tag Libraries?

In the previous chapters, you learned about JavaBeans and how to use them in JSP pages. The idea behind this is to allow the developer to replace Java code in the JSP page with XML notation. This is cleaner and reduces errors. JavaBeans allow you to separate your applications into presentation code (contained in the JSP) and business logic (contained in the beans). JavaBeans is a good start, but doesn't take us too far. If we want to do stuff, beyond getting and setting values, we need to use custom tags. Because this need made its way into Sun's Java wish list, we now have custom tags, which are tags of your design backed up with tag libraries. The main reasons as to why Tag Libraries are used so commonly are:

1. Simple - People who have less geek in them should be able to understand and use them.
2. Portable - The functionality of a tag library must be usable in any JSP container.
3. Expressive - This technology will support nested actions, scripting elements inside action bodies, and creation, use, and updating of scripting variables.
4. Flexible - Although the JSP specification currently only allows Java scripts, the architecture is designed to add other scripting languages.
5. Reusable - Once you write a tag handler, like a JavaBean, you can use it easily in many projects.

Steps to Create a Tag Library:

Below are the steps as to how to create a tag library and use it in your code.

1. Write and compile a simple tag handler that services the custom tag in your JSP (JSP custom tag attribute invokes a setter method in tag handler). Place the tag handler Java class files for your tags in the WEB-INF/classes directory of your Web application.
2. Write the tag library descriptor (TLD), which defines the tag library including the name of the tag handler class and attributes. Place it in its directory, which you declare in the deployment descriptor (CATALINA_HOME/webapps/examples/WEB-INF/xyz.tld).
3. Declare the Tag Library Descriptor in the Web application deployment descriptor (CATALINA_HOME/webapps/examples/WEB-INF/web.xml):
4. Declare the tag library in your JSP source using the JSP directive.
5. Use the custom tag in your JSP page.
6. Restart your container and test your tag library.

An Example Tag Library Usage:

Before we jump on to the nuances of tag library usage, lets check out a simple example. This example will give you a fair idea of how tag libraries work. You already know the steps of creating a tag library. Lets look at an example that does just that.

Our example is going to use 4 files:
1. The .java Tag Handler class
2. The .tld Tag Library Definition file
3. Web.xml and
4. The JSP that uses the tag library.

Source code of web.xml:
< web-app >
< ! - - XML removed to conserve space - - >
< taglib >
< taglib – uri >
http://www.myCompany.com/myTagLibrary
< / taglib-uri >
< taglib – location >
/WEB-INF/myTagLibrary.tld
< / taglib-location >
< / taglib >
< ! - - XML removed to conserve space - - >
< / web-app >


Source code of the JSP:

< html >
< head >
< % @ taglib uri=http://www.myCompany.com/myTagLibrary prefix="myLibrary" % >
< / head >

< body >
< myLibrary:guessColors color="red" / >.
< br / >
Your first tag library is gonna work.
< / body >
< / html >

Source code of the Tag Library Descriptor:

< ? xml version="1.0" encoding="ISO-8859-1" ? >
< taglib >
< tlibversion > 1.0 < / tlibversion >
< jspversion > 1.1 < / jspversion >
< shortname > myLibrary < / shortname >
< uri > http://www.myCompany.com/myTagLibrary < / uri >
< info > My first tag library< / info >

< tag >
< name > guessColors < / name >
< tagclass > examples.MyColorHandlerTag< / tagclass >
< info > Simply sends back some text < / info >
< attribute >
< name > color < / name >
< required > true < / required >
< rtexprvalue > false < / rtexprvalue >
< / attribute >
< / tag >
< / taglib >

Source Code of the Tag Library Handler:

package examples;

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
* Given a color, simply send back the value.
*
* @author Anand V
*/
public class MyColorHandlerTag
extends javax.servlet.jsp.tagext.TagSupport
{
/** color attribute */
private String color;

/**
* Processes this tag.
*/
public int doStartTag() throws JspException
{

// build up some HTML
String html = "The current color is: ";

// add to output stream
try {
pageContext.getOut().write( html + color);
} catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}

return EVAL_BODY_INCLUDE;
}

/**
* JavaBeans-style property setter for color.
*
*/
public void setColor(String s)
{
this.color = s;
}
}

By successfully using the above 4 files in your source code, you can use the tag library in your code and utilize its features.

Previous Chapter: Self Test - Chapters 38 to 43

Next chapter: Chapter 45 - Custom Tags

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers