Expression Language functions

We can add some function support from Java to EL. Not much, actually, but in this context we should care only of presentation, so we shouldn't expected to have a large need of functions here.

The fundamental limitation is that we can use just public static method defined in a plain old Java class. Than we should describe in a Tag Library Descriptor (usually called TLD file), that is an XML file that should be made available to the project being stored under the /WEB-INF directory. Finally we should put a taglib directive in our JSP page to let the function declaration be in the scope.

The function

Let's say we want to show a random number in (1 .. 6) to the user, so we write this class:
package ch08;

public class DiceRoller {
    public static int rollDice() {
        return (int) ((Math.random() * 6) + 1);
    }
}
The Tag Library Descriptor

Now we create a new file in the WEB-INF folder named something like myFunctions.tld, and we put in it this stuff:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
    <tlib-version>1.2</tlib-version>
    <uri>DiceFunctions</uri>
    <function>
        <name>rollIt</name>
        <function-class>ch08.DiceRoller</function-class>
        <function-signature>int rollDice()</function-signature>
    </function>
</taglib>
I get a few warning from Eclipse on the first line of the file, but you could safely ignore them. I reckon the support to TLD is just not that good.

Notice that we actually renamed the int ch08.DiceRoller.rollDice() to rollIt(), that is now the name we should use in our JSP page.

The taglib tag

In our JSP page we put this taglib directive before the html tag:
<%@ taglib prefix="mine" uri="DiceFunctions"%>
The uri we use here is the one we have defined in our TLD file. The prefix is the one we should call to have access in the JSP page to the functions defined in our TLD.

The function call

So now we can write the code that call our function:
You get: ${mine:rollIt()}
I wrote this post while reading the eighth chapter of Head First Servlet and JSP, a good book to read if you are interested in this stuff.

No comments:

Post a Comment