Appendix B. JSP Expression Language Reference

This appendix captures, at one location, the syntactical details of the Expression Language (EL) in JSP 2. It serves as a quick reference for resolving usage questions as you apply EL in your JSP programs.

EL Expressions

EL is a language that complements JSTL, enabling the creation of completely scriptless JSPs. As its name implies, EL is a language that revolves around the evaluation of expressions. EL expressions provide powerful access to JavaBeans, Java collections, Java maps, and Java arrays. This capability eliminates the need to perform access through Java coding from within scripting elements. An EL expression is always dynamically evaluated at request time. All EL expressions are contained in the following notation:

${.... EL expression..... }

El expressions may appear in two distinct locations in a JSP page:

  • In-line with template data

  • Within attribute values of tags (for example, JSTL tags)

EL expressions in-line with template data

An EL expression can be used to render a textual string in-line with template data—for example, as a constant EL arithmetic expression:

<b>There are ${5 + 1} bears in the cave.</b>

Another example demonstrates the use of EL to address a property of a nested JavaBeans:

<b>The total cost for this order is ${order.totals.afterTax}.</b>

EL expressions in attribute values

EL expressions are also used for the attribute values of certain tags. Namely, EL expressions are frequently found in the attribute values of tags in the JSTL. For example, the <c:if> JSTL tag uses an EL logical expression for its test attribute value:

<c:if test="${salary > 100000}">
<b>Rich cousin!</b><br/>
</c:if>

Accessing Arrays, Maps, Object Properties, and Collections

The most powerful aspect of EL is the ease with which it can be used to access Java arrays, maps, object properties, and collections. Access to all of these types is unified via the dot (.) or [ ] (square brackets) notation. The rules of access are designed in such a way that the most "obvious" way of accessing an element, given that you're familiar with Java programming, will work as intended.

Object properties access

To access the minQual property of a Java object called member, for example, use the following EL:

<b>You must earn ${member.minQual} points to maintain your membership.</b>

You can also use the equivalent [] notation:

<b>You must earn ${member["minQual"]} points to maintain your membership.</b>

The getMinQual() getter method of the object will be invoked to obtain the value to be rendered.

Array member access

To access the ninth element in a Java array named callHistory, you can use the following EL:

<b>In the most recent call to the customer, ${callHistory[8]} is discussed .</b>

Java map access

A Java Map typed object provides mapping between a set of keys and a set of values. Using EL, as long as the key values can be converted to strings, the elements in the Map can be directly accessed using EL.

For example, to access the value associated with the key "Mumbai" in a HashMap (a concrete implementation of a Java Map) called temperature, the following EL can be used:

<b>The temperature now is ${temperature.Mumbai}.  </b>

The following code is equivalent to the preceding code:

<b>The temperature now is ${temperature["Mumbai"]}.  </b>

Java collection access

EL can readily work with any Java Collection object (i.e. objects that implement the java.util.Collection interface). Iterative access is achieved in collaboration with JSTL's <c:forEach> tag (see Appendix C, "JSTL Reference"). Individual elements of a List- based collection can be accessed via the following EL:

<tr><td>${memberList[3]} </td></tr>

The preceding code will call the memberList.get(3) method and coerce the result to a string for rendering. The fourth element in the list will be displayed.

Elements of EL Expressions

EL expressions are composed of named variables, literals, operators, and functions.

Named variables

Any named variables within EL expressions are first checked against the available EL implicit objects (see the "Implicit Objects" section later in this appendix). If the named variable does not correspond to any implicit object, the EL runtime will search through the different scopes for an attribute with the specified name. It will search the scopes in the order of page

Named variables

Literals

Literals are constants that can be used within EL. The following table shows the different types of literals available in EL.

Literal Type

Description

Boolean

The value true or false

Integer

An integer numeric value

Floating point

A floating-point numeric value

String

A string within either double or single quotes

Null

The value null

Operators

Operators fall into four categories:

  • Arithmetic operators

  • Logical operators

  • Comparison operators

  • The empty prefix operator

Arithmetic operators

All the basic arithmetic operators that you are familiar with are available within EL expressions. This includes addition, subtraction, multiplication, division, and modulus. The following table lists these operators.

Operator

Symbol

Addition

+

Subtraction

-

Multiplication

*

Division

/ or div

Modulo

% or mod

Logical operators

In EL, logical operators can be used to combine multiple boolean-valued sub-expressions. The logical operators supported by EL are shown in the following table.

Operator

Symbol

And

&& or and

Or

|| or or

Not

! or not

Comparison (relational) operators

EL supports a range of comparison operators found in most programming languages. Each of the operators has a symbolic form and an abbreviated textual form. The following table enumerates the available comparison operators.

Operator

Symbol

Greater than

> or gt

Greater than or equal to

>= or ge

Less than

< or lt

Lesser than or equal to

<= or le

Equal to

== or eq

Not equal to

!= or ne

The empty operator

The empty operator is a unary operator that can be used to test certain conditions. The conditions tested will depend on the type of the actual operand. The following table shows the empty values for the different operand types.

Operand Data Type

Empty Value

String

""

Any named variable

Null

Array

No elements

Map

No elements

List/Collection

No elements

Operator precedence

As with most programming languages, parentheses ( ) can be used to control the exact precedence of the operators.

Otherwise, the precedence follows this order:

  1. [] and .; cannot be overridden by parentheses

  2. ()

  3. Unary operators ( -, !, empty)

  4. * / %

  5. + -

  6. < > <= >=

  7. == !=

  8. &&

  9. ||

  10. ? :

Functions

Functions can be used within EL to transform values of variables or other expressions. The general syntax to call a function within EL is as follows:

xx:fname( arg1, arg2, ..... )

Here, xx is the prefix of a tag library that contains the EL function, fname is the name of the function, and arg1, arg2, .... is a list of arguments for the function.

EL functions must be packaged as part of a tag library.

Namespace and EL functions

EL functions use the same namespace concept that custom tags use. They must be defined within the Tag Library Descriptor (TLD).

For example, for an EL function called rankOf(), you may use the following EL expression:

${wf:rankOf(name, level)}

Before using the preceding EL expression, the wf namespace/prefix must be defined in a <%@ taglib %> directive earlier—in this case, a <%@ taglib %> directive similar to the following:

<%@ taglib prefix="wf" uri="http://www.wrox.com/begjsp/el-functions-taglib" %>

EL function implementation: static methods of a Java class

EL functions are implemented in the Java programming language. They must be defined as static methods in a Java class. They can return a value of any data type, although String return types are most useful when rendering in EL expressions.

An EL function implemented as a static method can also have any number of arguments. The TLD must describe the return data type and the arguments' data type.

For example, the following TLD fragment describes a rankOf() EL function that returns a String, and takes a String and an int as arguments:

<function>
  <description>Function to determine a member's rank</description>
  <name>rankOf</name>
  <function-class>com.wrox.begjsp.ch15.ElFuncs</function-class>
  <function-signature>String rankOf(String,  int )</function-signature>
 </function>

Type Conversions

To make programming in EL as simple as possible, EL has a set of type conversion rules that tries to "do the right thing" under most circumstances. This set of rules governs what happens when operands or arguments of an inappropriate type are supplied in expressions.

Coercion: automatic type conversion

Coercion, or automatic type conversion, occurs when the input type does not match the required type. For example, the attribute of a tag may require an integer value, but the input value is a string. Before this conversion can happen, EL will always first "box" a primitive type, as explained next.

Boxing and unboxing

Boxing is simply the action of creating an associated Java object from a primitive type. The following table shows the common primitive types and their boxed form. Unboxing refers to the action of creating a primitive typed value from the associated Java object.

Primitive Type

Boxed Type

int

Integer

long

Long

double

Double

char

Character

boolean

Boolean

Coercion to String

Variable values are coerced to a String type as follows:

  1. First box the variable if it is primitive.

  2. Use the toString() method of the wrapping object to obtain the String equivalent.

Null values are returned as an empty string, "". An error will result if the call to toString() throws an exception.

Coercion to Number

Number types include short, int, float, double, and their boxed types.

Variables of any type are coerced to a number type by first boxing them if necessary, and then taking one of the following actions:

  • If the type is String, use the valueOf() method to get its value; "" empty string will return 0.

  • If the type is Character, use new Short((short) v.charValue()), assuming the Character variable is called v.

  • Unbox the variable if necessary.

Null values are returned as 0. If the type is a Boolean, an error will result. Numbers can always be converted successfully among themselves (for example, Integer to Float). If the call to valueOf() throws an exception, an error will result.

Coercion to Character

Variable values are coerced to Character type in the following manner:

  • If the type is a Number type, first it is coerced to the type Short, and then a Character is returned that is numerically equivalent to the short value.

  • If the type is String, the method charAt(0) is used to obtain the Character. This is essentially the first character of the string.

Coercing a null value causes (char) 0 to be returned as the result. A Boolean incoming type will cause an error.

Implicit Objects

Implicit objects are built-in objects that can be used within any EL expression. This concept is similar to implicit objects in JSP. In fact, EL can be used to access equivalent JSP implicit objects through the pageContext implicit object.

However, accessing JSP implicit objects is unnecessary because the set of EL implicit objects makes accessing relevant values substantially easier.

There are 11 EL implicit objects, which can be classified into five major categories:

  • JSP implicit object: pageContext

  • Convenience scoping access: pageScope, requestScope, sessionScope, applicationScope

  • Convenience parameter access: param, paramValues

  • Convenience header access: header, headerValues, cookies

  • Convenience initialization parameter access: initParam

The pageContext implicit object

This is the same as the JSP implicit object of the same name. The properties of this implicit object can be used to access the various JSP implicit objects.

For example, pageContext.request is the same as the request JSP implicit object, and pageContext.servletContext is the same as the JSP application implicit object. For more details on the available properties, see a description of the pageContext JSP implicit object in Appendix A.

The pageScope implicit object

The pageScope implicit object provides a map of all the available attributes in the page scope. In EL, values of a Map can be accessed via the [] notation or the. notation.

For example, to render the value of an attribute named selectedRow in the page scope, the following EL can be used:

${pageScope.selectedRow}

The following EL is equivalent:

${pageScope["selectedRow"]}

The requestScope implicit object

The requestScope implicit object provides a map of all the available attributes in the request scope. In EL, values of a map can be accessed via the [] notation or the dot (.) notation.

For example, to render the value of an attribute named currentCert in the request scope, the following EL can be used:

${requestScope.currentCert}

The following EL is equivalent:

${requestScope["currentCert"]}

Note that in some cases, if the incoming request is originating from another Web resource (for example, a PERL script), the name of the attribute may actually contain embedded dot (.) characters. In this case, you must use the second EL syntax shown above—the [] notation to access the value of the attribute.

The sessionScope implicit object

The sessionScope implicit object provides a Map of all the available attributes in the session scope. In EL, values of a Map can be accessed via either the [] notation or the dot (.) notation.

For example, to render the value of an attribute named orderTotal in the session scope, the following EL can be used:

${sessionScope.orderTotal}

The following EL is equivalent:

${sessionScope["orderTotal"]}

The applicationScope implicit object

The applicationScope implicit object provides a map of all the available attributes in the application scope. In EL, values of a map can be accessed via the [] notation or the dot (.) notation.

For example, to render the value of an attribute named productCategories in the application scope, the following EL can be used:

${applicationScope.productCategories}

The following EL is equivalent:

${applicationScope["productCategories"]}

The param implicit object

The param implicit object is a map containing all the incoming request parameters. The keys of the map are the names of the parameters, and the values are the corresponding values. In EL, values of a map can be accessed via the [] notation or the dot (.) notation.

For example, to render the value of a request parameter named address1, the following EL can be used:

${param.address1}

The following EL is equivalent:

${param["address1"]}

The paramValues implicit object

The paramValues implicit object is a map providing access to all multivalued incoming request parameters. The keys of the map are the names of the parameters, and the values are arrays of strings (String []) with the corresponding values. In EL, values of a map can be accessed via the [] notation or the dot (.) notation.

For example, to access the values in a multivalued request parameter named itemsPurchased, the following EL can be used. Of course, you are likely to use <c:forEach> to iterate through the resulting array value.

${paramValues.itemsPurchased}

Equivalently, the following EL can also be used obtain the array:

${paramValues["itemsPurchased"]}

The header implicit object

The header implicit object is a Map containing all the HTTP headers. The keys of the Map are the names of the headers, and the values are the corresponding header values. In EL, values of a Map can be accessed via the [] notation or the dot ( . ) notation.

For example, to render the value of the HTTP header User-Agent, the following EL can be used:

${header["User-Agent"]}

The headerValues implicit object

The headerValues implicit object is a Map providing access to all multivalued HTTP request headers. The keys of the Map are the names of the headers, and the values are arrays of strings (String []) with the corresponding values. In EL, values of a Map can be accessed via the [] notation or the dot (.) notation.

For example, to access the values in a multivalued HTTP header named Accept-Encoding, the following EL can be used. Of course, you are likely to use <c:forEach> to iterate through the resulting array.

${header["Accept-Encoding"]}

The cookies implicit object

The cookies implicit object is a map containing all the values from available HTTP cookies with the request. The keys of the map are the names of the cookies, and the values are the corresponding values. In EL, values of a map can be accessed via either the [] notation or the dot (.) notation.

For example, to render the value of a cookie named lastLoginName, the following EL can be used:

${cookies.lastLoginName}

Equivalently, the following EL can also be used:

${cookies["lastLoginName"]}

Multiple cookies with the same name are not well supported by the implementation and should be avoided.

The initParam implicit object

The initParam implicit object is a Map containing all the values from initialization parameters for the current ServletContext (specified through the web.xml deployment descriptor; see Chapter 15, "JSP and Servlets," for more details). The keys of the map are the names of the initialization parameters, and the values are the corresponding values. In EL, values of a map can be accessed via either the [] notation or the dot (.) notation.

For example, to render the value of an initialization parameter named localOffice, the following EL can be used:

${initParam.localOffice}

The following EL is equivalent:

${initParam["localOffice"]}
..................Content has been hidden....................

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