Objective 4) EL code that uses functions

7.4) Given a scenario, write EL code that uses a function; write code for an EL function; and configure the EL function in a tag library descriptor.

Creating a a function for use within EL is very similar to creating a custom tag library (see chapter 9). A function for use with an EL must have a public static signature and it is mapped for use in the jsp via a Tag Library Descriptor file (a TLD). The following is a trivial example of a file with a method that can be used as an EL function.

package com.examulator;
public class Multiplier{
        public static int TimesTwo(int param){
                return param * 2;
            }
}

The TimesTwo method takes an int param and returns that parameter multiplied by two. Compile this file and place the .class output into the

WEB-INF\classes\com\examulator

directory.

Create a file called Multiplier.tld, with the following content

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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"> <tlib-version>1.0</tlib-version> <short-name>multiplier</short-name> <uri>arbitrary</uri> <function> <name>myfunction</name> <function-class>com.examulator.Multiplier</function-class> <function-signature>int TimesTwo(int)</function-signature> </function> </taglib>

And place it under the directory

WEB-INF\tlds

Note that the tag <function-signature> is not exactly like a method signature within a Java source file in that it only gives the type of any parameter, it does not give a name, i.e it does NOT have the form

int TimesTwo(int paramname>

The JSP that actually uses the function is as follows

<%@ taglib uri="arbitrary" prefix="mul" %>
<html>
${mul:myfunction(4)}
</html>

When you request this page it will show 8 in the returned page as the parameter 4 is multiplied by two. Of course in a real EL function the parameter passed to any EL function would usually be determined at runtime. Note that the taglib uri does not explicitly indicate where the tld file can be found and the system automatically searches through WEB-INF and its subdirectories to find a file with a matching uri. It also searches through jar files within the WEB-INF\LIB directories. The use of the string arbitrary is a rather poor choice of uri (after all the u does stand for unique) and you would be better advised to use some combination such as your own URL to ensure uniqueness and recognisability.


Other Sources

According to Mikalai Zaikin http://java.boot.by/wcd-guide/ch07s04.html

Last modified: Sunday, 20 September 2015, 07:21 PM