Learn Java for Web Development

(Tina Meador) #1

126 CHAPTER 3: Best Practices in Java EE Web Development


EL Functions

EL functions let you call Java method from JSP without using scripting. An EL function is mapped to
a static method of a Java class. This mapping is specified within a tag library descriptor (TLD), which
is explained later in this section. Listing 3-31 illustrates a simple Java method that returns the current
date and time.


Listing 3-31. Java Class with Public and Static Methods


1.package com.apress.elfunction;
2.
3.import java.text.SimpleDateFormat;
4.import java.util.Calendar;
5.
6.public class Now {
7.
8.public static String now() {
9.Calendar currentDate = Calendar.getInstance();
10.SimpleDateFormat formatter = new SimpleDateFormat(
11."yyyy/MMM/dd HH:mm:ss");
12.String now = formatter.format(currentDate.getTime());
13.
14.return now;
15.}
16.}
17.


The key requirement for a Java method to be used in an EL function is that the method must be
public and static. The three key players in an EL function are as follows:


   A Java method defined in a class
 A JSP page that invokes the Java method using EL
 A tag library descriptor file that maps the Java method in the Java class to the
JSP code that calls this Java method

Listing 3-32 illustrates the tag library descriptor file. A TLD is an XML file that declares a tag library.
This TLD file contains the declarations and mappings of one or more EL functions. Each function is
given a name and a specific method in a Java class that will implement the function.


Listing 3-32. Tag Library Descriptor


1.<?xml version="1.0" encoding="UTF-8"?>
2.<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
3.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4.xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5.http://java.sun.com/xml/ns/javaee/webjsptaglibrary_2_1.xsd">
6.1.2
7.elFunction
8.
9.now
10.

Free download pdf