What is expression language function?

When you want to use java method without scripting you have to use EL functions. You can write a simple EL function that calls a static method in a plane old java class you write. What ever the method returns used in the expression.

RULES:
-write a plain java class with public static method(with non void return type). Put this class in the /WEB-INF/classes directory.
-Write a tag library descriptor(TLD) file. The TLD provides the mapping between the java class that defines the function and the jsp that calls the function. Put it inside the /WEB-INF directory.
-Put a taglib directive in your JSP. It tells the container that the jsp is going to use TLD. Taglib directive is kind of like giving all your functions fully qualified names.
-Use expression language to invoke the function.

EXAMPLE:
We will do application to roll a dice using EL function.
FILES:

DiceRoller.java:
package beans;
public class DiceRoller {
public static int rollDice(){
return (int) ((Math.random()*6)+1);
}}

Mytld.tld:
<?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>mytld</short-name>
<uri>/WEB-INF/mytld</uri>(used in jsp uri=””)
<function>
<name>rollit</name> (used in jsp bhabani:rollit())
<function-class>beans.DiceRoller</function-class>
<function-signature>int rollDice()</function-signature>(actual function name in
DiceRoller.java)
</function>>
</taglib>

Index.jsp:
<%@taglib prefix="bhabani" uri="/WEB-INF/mytld"%>
<html>
<body>
DICE ROLLED:${bhabani:rollit()}
</body>
</html>

No comments:

Post a Comment