Create your own tld

We’ve been using Tag Libs before when we were using JSTL. It is also possible to create your own Tag Libs ands that’s what we’ll discuss in this tutorial.

First, let’s explain what a TLD is: a TLD is a definition file for a library existing out of one or more java classes. This means that I could write a series of classes and that anyone could use them in their jsp’s.

Let’s use the dice game again. Let’s say I to create a class that roll’s a die for me. This class has one method “roll”. In this method it creates a random number between 1 and 6 and returns it.

package dicegame;

public class DiceRoller {
  public static int roll() {
    return (int)((Math.random() * 6) + 1);
  }
}

Now we want our jsp to be able to call this method like this:

<html>
<head><title>Roll</title></head>
<body>
${roller:roll()}
</body>
</html>

Obviously this isn’t possible without extra code. The jsp doesn’t know what roller is. That’s why we’ll need to create a .tld file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://www.java.sun.com/xml/ns/j2ee" xsi:schemaLocation="http://www.java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
<tlib-version>1.2</tlib-version>
<uri>Roller</uri>
<function>
  <name>roll></name>
  <function-class>dicegame.DiceRoller</function-class>
  <function-signature>int roll()</function-signature>
</function>
</taglib>

First we define the name for our taglib (Roller), then we create a function named roll that refers to the roll method in the DiceRoller class.

Lastly we need to alter the jsp to make it work with the Roller tld.

<%@ taglib prefix=”roller” uri=”Roller” %>

If we place the code above at the top of our jsp, the jsp will be able to recognize our Roller tld and be able to call the function “roll”.

That concludes the tutorial about creating your own TLD.