Imagine you want your JSP to roll dice

You’ve decided it would be awesome to have a web-based dice-rolling service. That way, instead of hunting around behind desks and in the sofa cushions for real dice, a user could just go to your web page, click on the virtual dice, and voila! They roll! (Of course, you have no idea that a Google search will probably bring up, oh, about 4,420 sites that do this.)

  1. Write a Java class with a public static method.

    This is just a plain old Java class. The method MUST be public and static, and it can have arguments. It should (but isn’t required to) have a non-void return type. After all, the whole point is to call this from a JSP and get something back that you can use as part of the expression or to print out.

    Put the class file in the /WEB-INF/classes directory structure (matching the appropriate package directory structure, just like you would with any other class).

  2. Write a Tag Library Descriptor (TLD) file.

    For an EL function, the TLD provides a mapping between the Java class that defines the function and the JSP that calls the function. That way, the function name and the actual method name can be different. You might be stuck with a class with a really stupid method name, for example, and maybe you want to provide a more obvious or intuitive name to page designers using EL. No problem—the TLD says, “This is the Java class, this is the method signature for the function (including return type) and this is the name we’ll use in EL expressions”. In other words, the name used in EL doesn’t have to be the same as the actual method name, and the TLD is where you map that.

    Put the TLD file inside the /WEB-INF directory. Name it with a .tld extension. (There are other places the TLD can go; we’ll talk about that in the next two chapters.)

  3. Put a taglib directive in your JSP.

    The taglib directive tells the Container, “I’m going to use this TLD, and in the JSP, when I want to use a function from this TLD, I’m going to prefix it with this name...” In other words, it lets you define the namespace. You can use functions from more than one TLD, and even if the functions have the same name, that’s OK. The taglib directive is kind of like giving all your functions fully-qualified names. You invoke the function by giving both the function name AND the TLD prefix. The prefix can be anything you like.

  4. Use EL to invoke the function.

    This is the easy part. You just call the function from an expression using ${prefix:name()}.

The function class, the TLD, and the JSP

image with no caption
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset