Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

What Is a JSP Page?

A Simple JSP Page Example

The Example JSP Pages

The Life Cycle of a JSP Page

Translation and Compilation

Execution

Buffering

Handling JSP Page Errors

Creating Static Content

Response and Page Encoding

Creating Dynamic Content

Using Objects within JSP Pages

Using Implicit Objects

Using Application-Specific Objects

Using Shared Objects

Unified Expression Language

Immediate and Deferred Evaluation Syntax

Immediate Evaluation

Deferred Evaluation

Value and Method Expressions

Value Expressions

Method Expressions

Defining a Tag Attribute Type

Deactivating Expression Evaluation

Literal Expressions

Resolving Expressions

Process of Expression Evaluation

EL Resolvers

Implicit Objects

Operators

Reserved Words

Examples of EL Expressions

Functions

Using Functions

Defining Functions

JavaBeans Components

JavaBeans Component Design Conventions

Creating and Using a JavaBeans Component

Setting JavaBeans Component Properties

Retrieving JavaBeans Component Properties

Using Custom Tags

Declaring Tag Libraries

Including the Tag Library Implementation

Reusing Content in JSP Pages

Transferring Control to Another Web Component

jsp:param Element

Including an Applet

Setting Properties for Groups of JSP Pages

Deactivating EL Expression Evaluation

Declaring Page Encodings

Defining Implicit Includes

Eliminating Extra White Space

Further Information about JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Unified Expression Language

The primary new feature of JSP 2.1 is the unified expression language (unified EL),which represents a union of the expression language offered by JSP 2.0 andthe expression language created for JavaServer Faces technology (seeChapter 10, JavaServer Faces Technology) version 1.0.

The expression language introduced in JSP 2.0 allows page authors to use simpleexpressions to dynamically read data from JavaBeans components. For example, thetest attributeof the following conditional tag is supplied with an EL expression that comparesthe number of items in the session-scoped bean namedcart with 0.

<c:if test="${sessionScope.cart.numberOfItems > 0}">  ...</c:if>

As explained inThe Life Cycle of a JSP Page, JSP supports a simple request/response life cycle, during whicha page is executed and the HTML markup is rendered immediately. Therefore, thesimple, read-only expression language offered by JSP 2.0 was well suited to theneeds of JSP applications.

JavaServer Faces technology, on the other hand, features a multiphase life cycle designed tosupport its sophisticated UI component model, which allows for converting and validating componentdata, propagating component data to objects, and handling component events. To facilitate thesefunctions, JavaServer Faces technology introduced its own expression language that included the following functionality:

  • Deferred evaluation of expressions

  • The ability to set data as well as get data

  • The ability to invoke methods

SeeUsing the Unified EL to Reference Backing Beans for more information on how to use the unified ELin JavaServer Faces applications.

These two expression languages have been unified for a couple reasons. One reasonis so that page authors can mix JSP content with JavaServer Faces tagswithout worrying about conflicts caused by the different life cycles these technologies support.Another reason is so that other JSP-based technologies could make use of theadditional features similarly to the way JavaServer Faces technology uses them. In fact,although the standard JSP tags and static content continue to use only thosefeatures present in JSP 2.0, authors of JSP custom tags can create tagsthat take advantage of the new set of features in the unified expressionlanguage.

To summarize, the new, unified expression language allows page authors to use simpleexpressions to perform the following tasks:

  • Dynamically read application data stored in JavaBeans components, various data structures, and implicit objects

  • Dynamically write data, such as user input into forms, to JavaBeans components

  • Invoke arbitrary static and public methods

  • Dynamically perform arithmetic operations

The unified EL also allows custom tag developers to specify which of thefollowing kinds of expressions that a custom tag attribute will accept:

  • Immediate evaluation expressions ordeferred evaluation expressions. An immediate evaluation expression is evaluated immediately by the JSP engine. A deferred evaluation expression can be evaluated later by the underlying technology using the expression language.

  • Value expression ormethod expression. A value expression references data, whereas a method expression invokes a method.

  • Rvalue expression orLvalue expression. An rvalue expression can only read a value, whereas an lvalue expression can both read and write that value to an external object.

Finally, the unified EL also provides a pluggable API for resolving expressions sothat application developers can implement their own resolvers that can handle expressions notalready supported by the unified EL.

This section gives an overview of the unified expression language features by explainingthe following topics:

Immediate and Deferred Evaluation Syntax

The unified EL supports both immediate and deferred evaluation of expressions.Immediate evaluation meansthat the JSP engine evaluates the expression and returns the result immediately whenthe page is first rendered.Deferred evaluation means that the technology using the expression languagecan employ its own machinery to evaluate the expression sometime later during thepage’s life cycle, whenever it is appropriate to do so.

Those expressions that are evaluated immediately use the${} syntax, which was introducedwith the JSP 2.0 expression language. Expressions whose evaluation is deferred use the#{} syntax, which was introduced by JavaServer Faces technology.

Because of its multiphase life cycle, JavaServer Faces technology uses deferred evaluation expressions.During the life cycle, component events are handled, data is validated, and othertasks are performed, all done in a particular order. Therefore, it must deferevaluation of expressions until the appropriate point in the life cycle.

Other technologies using the unified EL might have different reasons for using deferredexpressions.

Immediate Evaluation

All expressions using the${} syntax are evaluated immediately. These expressions can onlybe used within template text or as the value of a JSP tagattribute that can accept runtime expressions.

The following example shows a tag whose value attribute references an immediate evaluationexpression that gets the total price from the session-scoped bean named cart:

<fmt:formatNumber value="${sessionScope.cart.total}"/>

The JSP engine evaluates the expression,${sessionScope.cart.total}, converts it, and passes thereturned value to the tag handler.

Immediate evaluation expressions are always read-only value expressions. The expression shown above canonly get the total price from the cart bean; it cannot set thetotal price.

Deferred Evaluation

Deferred evaluation expressions take the form#{expr} and can be evaluated at otherphases of a page life cycle as defined by whatever technology is usingthe expression. In the case of JavaServer Faces technology, its controller can evaluatethe expression at different phases of the life cycle depending on how theexpression is being used in the page.

The following example shows a JavaServer FacesinputText tag, which represents a textfield component into which a user enters a value. TheinputText tag’svalueattribute references a deferred evaluation expression that points to thename property of thecustomer bean.

<h:inputText value="#{customer.name}" />

For an initial request of the page containing this tag, the JavaServer Facesimplementation evaluates the#{customer.name} expression during the render response phase of the lifecycle. During this phase, the expression merely accesses the value ofname fromthecustomer bean, as is done in immediate evaluation.

For a postback, the JavaServer Faces implementation evaluates the expression at different phasesof the life cycle, during which the value is retrieved from the request,validated, and propagated to thecustomer bean.

As shown in this example, deferred evaluation expressions can be value expressions thatcan be used to both read and write data. They can alsobe method expressions. Value expressions (both immediate and deferred) and method expressions are explainedin the next section.

Value and Method Expressions

The unified EL defines two kinds of expressions: value expressions and method expressions.Value expressions can either yield a value or set a value. Method expressionsreference methods that can be invoked and can return a value.

Value Expressions

Value expressions can be further categorized into rvalue and lvalue expressions.Rvalue expressions arethose that can read data, but cannot write it.Lvalue expressions can both read andwrite data.

All expressions that are evaluated immediately use the${} delimiters and are alwaysrvalue expressions. Expressions whose evaluation can be deferred use the#{} delimiters andcan act as both rvalue and lvalue expressions. Consider these two value expressions:

<taglib:tag value="${customer.name}" /><taglib:tag value="#{customer.name}" />

The former uses immediate evaluation syntax, whereas the latter uses deferred evaluation syntax.The first expression accesses thename property, gets its value, and the valueis added to the response and rendered on the page. The same thingcan happen with the second expression. However, the tag handler can defer theevaluation of this expression to a later time in the page life cycle,if the technology using this tag allows it.

In the case of JavaServer Faces technology, the latter tag’s expression is evaluatedimmediately during an initial request for the page. In this case, this expressionacts as an rvalue expression. During a postback, this expression can be usedto set the value of thename property with user input. In thissituation, the expression acts as an lvalue expression.

Referencing Objects Using Value Expressions

Both rvalue and lvalue expressions can refer to the following objects and theirproperties or attributes:

  • JavaBeans components

  • Collections

  • Java SE enumerated types

  • Implicit objects

SeeImplicit Objects for more detail on the implicit objects available with JSP technology.

To refer to these objects, you write an expression using a variable namewith which you created the object. The following expression references a JavaBeans componentcalledcustomer.

${customer}

The web container evaluates a variable that appears in an expression by lookingup its value according to the behavior ofPageContext.findAttribute(String), where theStringargument is the name of the variable. For example, when evaluating the expression${customer}, the container will look forcustomer in the page, request, session, and applicationscopes and will return its value. Ifcustomer is not found, null isreturned. A variable that matches one of the implicit objects described inImplicit Objectswill return that implicit object instead of the variable’s value.

You can alter the way variables are resolved with a custom ELresolver, which is a new feature of the unified EL. For instance, youcan provide an EL resolver that intercepts objects with the namecustomer, so that${customer} returns a value in the EL resolver instead. However, you cannot overrideimplicit objects in this way. SeeEL Resolvers for more information on ELresolvers.

You can set the variable name,customer, when you declare the bean. SeeCreating and Using a JavaBeans Component for information on how to declare a JavaBeans component for use inyour JSP pages.

To declare beans in JavaServer Faces applications, you use the managed bean facility.SeeBacking Beans for information on how to declare beans for use in JavaServerFaces applications.

When referencing an enum constant with an expression, you use aStringliteral. For example, consider this Enum class:

public enum Suit {hearts, spades, diamonds, clubs}

To refer to theSuit constant,Suit.hearts with an expression, you use theString literal,"hearts". Depending on the context, theString literal is converted to theenum constant automatically. For example, in the following expression in whichmySuit isan instance ofSuit,"hearts" is first converted to aSuit.hearts before itis compared to the instance.

${mySuit == "hearts"}
Referring to Object Properties Using Value Expressions

To refer to properties of a bean or an Enum instance, itemsof a collection, or attributes of an implicit object, you use the.or[] notation, which is similar to the notation used by ECMAScript.

So, if you wanted to reference thename property of thecustomer bean,you could use either the expression${customer.name} or the expression${customer["name"]}. The partinside the square brackets is aString literal that is the name ofthe property to reference.

You can use double or single quotes for theString literal. You canalso combine the[] and. notations, as shown here:

${customer.address["street"]}

Properties of an enum can also be referenced in this way. However,as with JavaBeans component properties, the Enum class’s properties must follow JavaBeans component conventions.This means that a property must at least have an accessor method calledget<Property> (where<Property> is the name of the property) so that anexpression can reference it.

For example, say you have an Enum class that encapsulates the names ofthe planets of our galaxy and includes a method to get themass of a planet. You can use the following expression to reference themethodgetMass of thePlanet Enum class:

${myPlanet.mass}

If you are accessing an item in an array or list, youmust use either a literal value that can be coerced to int orthe[] notation with an int and without quotes. The following examples couldall resolve to the same item in a list or array, assuming thatsocks can be coerced toint:

  • ${customer.orders[1]}

  • ${customer.orders.socks}

In contrast, an item in aMap can be accessed using a stringliteral key; no coercion is required:

${customer.orders["socks"]}

An rvalue expression also refers directly to values that are not objects, suchas the result of arithmetic operations and literal values, as shown by theseexamples:

  • ${"literal"}

  • ${customer.age + 20}

  • ${true}

  • ${57}

The unified expression language defines the following literals:

  • Boolean:true andfalse

  • Integer: as in Java

  • Floating point: as in Java

  • String: with single and double quotes;" is escaped as\", is escaped as\', and\ is escaped as\\

  • Null:null

You can also write expressions that perform operations on an enum constant. Forexample, consider the following Enum class:

public enum Suit {club, diamond, heart, spade }

After declaring an enum constant calledmySuit, you can write the following expressionto test ifmySuit isspade:

${mySuit == "spade"}

When the EL resolving mechanism resolves this expression it will invoke thevalueOfmethod of the Enum class with theSuit class and thespade type,as shown here:

mySuit.valueOf(Suit.class, "spade"}

SeeJavaBeans Components for more information on using expressions to reference JavaBeans components andtheir properties.

Where Value Expressions Can Be Used

Value expressions using the${} delimiters can be used in the following places:

  • In static text

  • In any standard or custom tag attribute that can accept an expression

The value of an expression in static text is computed and insertedinto the current output. Here is an example of an expression embedded instatic text:

<some:tag>    some text ${expr} some text</some:tag>

If the static text appears in a tag body, note that anexpressionwill not be evaluated if the body is declared to betagdependent(seeTags with Attributes).

Lvalue expressions can only be used in tag attributes that can accept lvalueexpressions.

There are three ways to set a tag attribute value using eitheran rvalue or lvalue expression:

  • With a single expression construct:

    <some:tag value="${expr}"/>
    <another:tag value="#{expr}"/>

    These expressions are evaluated and the result is coerced to the attribute’s expected type.

  • With one or more expressions separated or surrounded by text:

    <some:tag value="some${expr}${expr}text${expr}"/>
    <another:tag value="some#{expr}#{expr}text#{expr}"/>

    These kinds of expression are called acomposite expressions. They are evaluated from left to right. Each expression embedded in the composite expression is coerced to aString and then concatenated with any intervening text. The resultingString is then coerced to the attribute’s expected type.

  • With text only:

    <some:tag value="sometext"/>

    This expression is called aliteral expression. In this case, the attribute’sString value is coerced to the attribute’s expected type. Literal value expressions have special syntax rules. SeeLiteral Expressions for more information. When a tag attribute has an enum type, the expression that the attribute uses must be a literal expression. For example, the tag attribute can use the expression"hearts" to meanSuit.hearts. The literal is coerced toSuit and the attribute gets the valueSuit.hearts.

All expressions used to set attribute values are evaluated in the context ofan expected type. If the result of the expression evaluation does not matchthe expected type exactly, a type conversion will be performed. For example, theexpression${1.2E4} provided as the value of an attribute of typefloatwill result in the following conversion:

Float.valueOf("1.2E4").floatValue()

See section 1.18 of theJavaServer Pages 2.1 Expression Language Specification (available fromhttp://jcp.org/aboutJava/communityprocess/final/jsr245/) for the complete typeconversion rules.

Method Expressions

Another feature of the unified expression language is its support of deferred methodexpressions. A method expression is used to invoke an arbitrary public method, whichcan return a result. A similar feature of the unified EL is functions.Method expressions differ from functions in many ways.Functions explains more about the differencesbetween functions and method expressions.

Method expressions primarily benefit JavaServer Faces technology, but they are available to anytechnology that can support the unified expression language. Let’s take a look athow JavaServer Faces technology employs method expressions.

In JavaServer Faces technology, a component tag represents a UI component on apage. The component tag uses method expressions to invoke methods that perform someprocessing for the component. These methods are necessary for handling events that thecomponents generate and validating component data, as shown in this example:

<h:form>    <h:inputText                value="#{customer.name}"        validator="#{customer.validateName}"/>    <h:commandButton               action="#{customer.submit}" /></h:form>

TheinputText tag displays aUIInput component as a text field. Thevalidatorattribute of thisinputText tag references a method, calledvalidateName, in the bean,calledcustomer. The TLD (seeTag Library Descriptors) that defines theinputText tag specifieswhat signature the method referred to by thevalidator attribute must have.The same is true of thecustomer.submit method referenced by theaction attributeof thecommandButton tag. The TLD specifies that thesubmit method must returnanObject instance that specifies which page to navigate to next after thebutton represented by thecommandButton tag is clicked.

Thevalidation method is invoked during the process validation phase of the lifecycle, whereas thesubmit method is invoked during the invoke application phase ofthe life cycle. Because a method can be invoked during different phases ofthe life cycle, method expressions must always use the deferred evaluation syntax.

Similarly to lvalue expressions, method expressions can use the . and[]operators. For example,#{object.method} is equivalent to#{object["method"]}. The literal inside the[]is coerced toString and is used to find the name of themethod that matches it. Once the method is found, it is invoked orinformation about the method is returned.

Method expressions can be used only in tag attributes and only inthe following ways:

  • With a single expression construct, wherebean refers to a JavaBeans component andmethod refers to a method of the JavaBeans component:

    <some:tag value="#{bean.method}"/>

    The expression is evaluated to a method expression, which is passed to the tag handler. The method represented by the method expression can then be invoked later.

  • With text only:

    <some:tag value="sometext"/>

    Method expressions support literals primarily to supportaction attributes in JavaServer Faces technology. When the method referenced by this method expression is invoked, it returns theString literal, which is then coerced to the expected return type, as defined in the tag’s TLD.

Defining a Tag Attribute Type

As explained in the previous section, all kinds of expressions can be usedin tag attributes. Which kind of expression and how that expression is evaluated(whether immediately or deferred) is determined by thetype attribute of the tag’sdefinition in the TLD (seeTag Library Descriptors) file that defines the tag.

If you plan to create custom tags (seeChapter 8, Custom Tags in JSP Pages), you need tospecify for each tag in the TLD what kind of expression it accepts.Table 5-2 shows the three different kinds of tag attributes that accept EL expressions,and gives examples of expressions they accept and the type definitions of theattributes that must be added to the TLD. You cannot use#{}syntax for a dynamic attribute, meaning an attribute that accepts dynamically-calculated values at runtime.Section 2.3.2 of the JavaServer Pages 2.1 specification refers to these attributes. Neithercan you use the${} syntax for a deferred attribute.

Table 5-2 Definitions of Tag Attributes That Accept EL Expressions

Attribute Type

Example Expression

Type AttributeDefinition

dynamic

"literal"

<rtexprvalue>true</rtexprvalue>

${literal}

<rtexprvalue>true</rtexprvalue>

deferred value

"literal"

<deferred-value>   <type>java.lang.String</type></deferred-value>

#{customer.age}

<deferred-value>   <type>int</type></deferred-value>

deferred method

"literal"

<deferred-method>   <method-signature>      java.lang.String submit()   </method-signature><deferred-method>

#{customer.calcTotal}

<deferred-method>   <method-signature>      double calcTotal(int, double)   </method-signature></deferred-method>

In addition to the tag attribute types shown inTable 5-2, you canalso define an attribute to accept both dynamic and deferred expressions. In thiscase, the tag attribute definition contains both anrtexprvalue definition set totrue and either adeferred-value ordeferred-method definition.

Deactivating Expression Evaluation

Because the patterns that identify EL expressions,${ } and#{ }, were not reserved inthe JSP specifications before JSP 2.0, there might exist applications in which suchpatterns are intended to pass through verbatim. To prevent the patterns from beingevaluated, you can deactivate EL evaluation using one of the following methods:

  • Escape the#{ or${ characters in the page.

  • Configure the application with a JSP Property Group.

  • Configure the page with the page directive.

To escape the#{ or${ characters in the page, you use the\ character as follows:

some text \#{ some more\${ text<my:tag someAttribute="sometext\#{more\${text" />

Another way to deactivate EL evaluation is by using a JSP propertygroup to either allow the#{ characters as aString literal using thedeferred-syntax-allowed-as-literalsubelement, or to treat all expressions as literals using theel-ignored subelement:

<jsp-property-group>    <deferred-syntax-allowed-as-literal>        true    </deferred-syntax-allowed-as-literal></jsp-property-group>

or

<jsp-property-group>    <el-ignored>true</el-ignored></jsp-property-group>

Finally, you can configure the page with thepage directive to either acceptthe#{ characters asString literals with thedeferredSyntaxAllowedAsLiteral attribute, or to ignore allEL expressions using theisELIgnored attribute:

<%@page ... deferredSyntaxAllowedAsLiteral="true" %>

or

<%@ page isELIgnored ="true" %>

The valid values of these attributes aretrue andfalse. IfisELIgnoredistrue, EL expressions are ignored when they appear in static text ortag attributes. If it isfalse, EL expressions are evaluated by the container onlyif the attribute hasrtexprvalue set totrue or the expression is adeferred expression.

The default value ofisELIgnored varies depending on the version of the webapplication deployment descriptor. The default mode for JSP pages delivered with a Servlet2.4 descriptor is to evaluate EL expressions; this automatically provides the default thatmost applications want. The default mode for JSP pages delivered using a descriptorfrom Servlet 2.3 or before is to ignore EL expressions; this provides backwardcompatibility.

Literal Expressions

A literal expression evaluates to the text of the expression, which is oftypeString. It does not use the${} or#{} delimiters.

If you have a literal expression that includes the reserved${} or#{} syntax, you need to escape these characters as follows.

  • By creating a composite expression as shown here:

    ${’${’}exprA}
    #{’#{’}exprB}

    The resulting values would then be the strings${exprA} and#{exprB}.

  • The escape characters\$ and\# can be used to escape what would otherwise be treated as an eval-expression:

    \${exprA}
    \#{exprB}

    The resulting values would again be the strings${exprA} and#{exprB}.

When a literal expression is evaluated, it can be converted to another type.Table 5-3 shows examples of various literal expressions and their expected types and resultingvalues.

Table 5-3 Literal Expressions

Expression

Expected Type

Result

Hi

String

Hi

true

Boolean

Boolean.TRUE

42

int

42

Literal expressions can be evaluated immediately or deferred and can be either valueor method expressions. At what point a literal expression is evaluated depends onwhere it is being used. If the tag attribute that uses the literalexpression is defined as accepting a deferred value expression, then the literal expressionreferences a value and is evaluated at a point in the life cyclethat is determined by where the expression is being used and to whatit is referring.

In the case of a method expression, the method that is referencedis invoked and returns the specifiedString literal. ThecommandButton tag of theGuess Number application uses a literal method expression as a logical outcome totell the JavaServer Faces navigation system which page to display next. SeeNavigation Modelfor more information on this example.

Resolving Expressions

The unified EL introduces a new, pluggable API for resolving expressions. The mainpieces of this API are:

  • TheValueExpression class, which defines a value expression

  • TheMethodExpression class, which defines a method expression

  • AnELResolver class that defines a mechanism for resolving expressions

  • A set ofELResolver implementations, in which each implementation is responsible for resolving expressions that reference a particular type of object or property

  • AnELContext object that saves state relating to EL resolution, holds references to EL resolvers, and contains context objects (such asJspContext) needed by the underlying technology to resolve expressions

Most application developers will not need to use these classes directly unless theyplan to write their own custom EL resolvers. Those writing JavaServer Faces customcomponents will definitely need to useValueExpression andMethodExpression. This section detailshow expressions are resolved for the benefit of these developers. It does notexplain how to create a custom resolver. For more information on creating customresolvers, see the articleThe Unified Expression Language, Ryan Lubke et al., located athttp://java.sun.com/products/jsp/reference/techart/unifiedEL.html.You can also refer toRequest Processing, which explains how the Duke’s Bankapplication uses a custom resolver.

Process of Expression Evaluation

When a value expression that is included in a page is parsedduring an initial request for the page, aValueExpression object is created to representthe expression. Then, theValueExpression object’sgetValue method is invoked. This methodwill in turn invoke thegetValue method of the appropriate resolver. Asimilar process occurs during a postback whensetValue is called if the expression isan lvalue expression.

In the case of a method expression, aBeanELResolver is used to findthe object that implements the method to be invoked or queried. Similarly tothe process for evaluating value expressions, when a method expression is encountered, aMethodExpression object is created. Subsequently, either theinvoke orgetMethodInfo method of theMethodExpressionobject is called. This method in turn invokes theBeanELResolver object’sgetValue method.ThegetMethodInfo is mostly for use by tools.

After a resolver completes resolution of an expression, it sets thepropertyResolvedflag of theELContext totrue so that no more resolvers areconsulted.

EL Resolvers

At the center of the EL machinery is the extensibleELResolver class. Aclass that implementsELResolver defines how to resolve expressions referring to aparticular type of object or property. In terms of the following expression, aBeanELResolver instance is called the first time to find thebase object,employee, which is a JavaBeans component. Once the resolver finds the object, itis called again to resolve theproperty,lName of the employee object.

${employee.lName}

The unified EL includes a set of standard resolver implementations.Table 5-4 liststhese standard resolvers and includes example expressions that they can resolve.

Table 5-4 Standard EL Resolvers

Resolver

Example Expression

Description

ArrayELResolver

${myArray[1]}

Returns thevalue at index 1 in the array calledmyArray

BeanELResolver

${employee.lName}

Returns the value ofthelName property of theemployee bean

ListELResolver

${myList[5]}

Returns the value at index 5ofmyList list

MapELResolver

${myMap.someKey}

Returns the value stored at the key,someKey, in theMap,myMap

ResourceBundleELResolver

${myRB.myKey}

Returns the message atmyKey in the resource bundle calledmyRB

Depending on the technology using the unified EL, other resolvers might be available.In addition, application developers can add their own implementations ofELResolver to supportresolution of expressions not already supported by the unified EL by registering themwith an application.

All of the standard and custom resolvers available to a particular application arecollected in a chain in a particular order. This chain of resolversis represented by aCompositeELResolver instance. When an expression is encountered, theCompositeELResolver instance iteratesover the list of resolvers and consults each resolver until it finds onethat can handle the expression.

If an application is using JSP technology, the chain of resolvers includes theImplicitObjectELResolver and theScopedAttributeELResolver. These are described in the following section.

See section JSP 2.9 of the JavaServer Pages 2.1 specification to find outthe order in which resolvers are chained together in aCompositeELResolver instance.

To learn how to create a custom EL resolver, seeThe Unified Expression Language .

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:

  • In addition, several implicit objects are available that allow easy access to the following objects:

    • param: Maps a request parameter name to a single value

    • paramValues: Maps a request parameter name to an array of values

    • header: Maps a request header name to a single value

    • headerValues: Maps a request header name to an array of values

    • cookie: Maps a cookie name to a single cookie

    • initParam: Maps a context initialization parameter name to a single value

  • Finally, there are objects that allow access to the various scoped variables described inUsing Scope Objects.

    • pageScope: Maps page-scoped variable names to their values

    • requestScope: Maps request-scoped variable names to their values

    • sessionScope: Maps session-scoped variable names to their values

    • applicationScope: Maps application-scoped variable names to their values

JSP 2.1 provides two EL resolvers to handle expressions that reference these objects:ImplicitObjectELResolver andScopedAttributeELResolver.

A variable that matches one of the implicit objects is evaluated byImplicitObjectResolver, which returns the implicit object. This resolver only handles expressions with abase ofnull. What this means for the following expression is that theImplicitObjectResolver resolves thesessionScope implicit object only. Once the implicit object is found,theMapELResolver instance resolves theprofile attribute because theprofile object represents a map.

${sessionScope.profile}

ScopedAttributeELResolver evaluates a single object that is stored in scope. LikeImplicitObjectELResolver, it alsoonly evaluates expressions with a base ofnull. This resolver essentially looks foran object in all of the scopes until it finds it, according tothe behavior ofPageContext.findAttribute(String). For example, when evaluating the expression${product}, the resolverwill look forproduct in the page, request, session, and application scopes andwill return its value. Ifproduct is not found,null is returned.

When an expression references one of the implicit objects by name, the appropriateobject is returned instead of the corresponding attribute. For example,${pageContext} returns thePageContext object, even if there is an existingpageContext attribute containing some other value.

Operators

In addition to the. and[] operators discussed inValue and Method Expressions, the JSP expressionlanguage provides the following operators, which can be used in rvalue expressions only:

  • Arithmetic:+,- (binary),*,/ anddiv,% andmod,- (unary)

  • Logical:and,&&,or,||,not,!

  • Relational:==,eq,!=,ne,<,lt,>,gt,<=,ge,>=,le. Comparisons can be made against other values, or against boolean, string, integer, or floating point literals.

  • Empty: Theempty operator is a prefix operation that can be used to determine whether a value isnull or empty.

  • Conditional:A ? B : C. EvaluateB orC, depending on the result of the evaluation ofA.

The precedence of operators highest to lowest, left to right is asfollows:

  • [] .

  • () (used to change the precedence of operators)

  • - (unary)not ! empty

  • * / div % mod

  • + - (binary)

  • < > <= >= lt gt le ge

  • == != eq ne

  • && and

  • || or

  • ? :

Reserved Words

The following words are reserved for the JSP expression language and should notbe used as identifiers.

and

or

not

eq

ne

lt

gt

le

ge

true

false

null

instanceof

empty

div

mod

Note that many of these words are not in the language now,but they may be in the future, so you should avoid using them.

Examples of EL Expressions

Table 5-5 contains example EL expressions and the result of evaluating them.

Table 5-5 Example Expressions

EL Expression

Result

${1 > (4/2)}

false

${4.0 >= 3}

true

${100.0 == 100}

true

${(10*10) ne 100}

false

${'a' < 'b'}

true

${'hip' gt 'hit'}

false

${4 > 3}

true

${1.2E4 + 1.4}

12001.4

${3 div 4}

0.75

${10 mod 4}

2

${!empty param.Add}

False ifthe request parameter namedAdd is null or an empty string.

${pageContext.request.contextPath}

The context path.

${sessionScope.cart.numberOfItems}

Thevalue of thenumberOfItems property of the session-scoped attribute namedcart.

${param['mycom.productId']}

The value ofthe request parameter namedmycom.productId.

${header["host"]}

The host.

${departments[deptName]}

The value of the entry nameddeptNamein thedepartments map.

${requestScope[’javax.servlet.forward.servlet_path’]}

The value of the request-scoped attribute namedjavax.servlet.forward.servlet_path.

#{customer.lName}

Gets thevalue of the propertylName from thecustomer bean during an initialrequest. Sets the value oflName during a postback.

#{customer.calcTotal}

The return value of themethodcalcTotal of thecustomer bean.

Functions

The JSP expression language allows you to define a function that can beinvoked in an expression. Functions are defined using the same mechanisms as customtags (seeUsing Custom Tags andChapter 8, Custom Tags in JSP Pages).

At first glance, functions seem similar to method expressions, but they are differentin the following ways:

  • Functions refer to static methods that return a value. Method expressions refer to non-static, arbitrary public methods on objects.

  • Functions are identified statically at translation time, whereas methods are identified dynamically at runtime.

  • Function parameters and invocations are specified as part of an EL expression. A method expression only identifies a particular method. The invocation of that method is not specified by the EL expression; rather, it is specified in the tag attribute definition of the attribute using the method expression, as described inDefining a Tag Attribute Type.

Using Functions

Functions can appear in static text and tag attribute values.

To use a function in a JSP page, you use ataglibdirective to import the tag library containing the function. Then you preface thefunction invocation with the prefix declared in the directive.

For example, the date example pageindex.jsp imports the/functions library and invokesthe functionequals in an expression:

<%@ taglib prefix="f" uri="/functions"%>...        <c:when            test="${f:equals(selectedLocaleString,                localeString)}" >

In this example, the expression referencing the function is using immediate evaluation syntax.A page author can also use deferred evaluation syntax to reference a functionin an expression, assuming that the attribute that is referencing the function canaccept deferred expressions.

If an attribute references a function with a deferred expression then the functionis not invoked immediately; rather, it is invoked whenever the underlying technology usingthe function determines it should be invoked.

Defining Functions

To define a function, program it as a public static method in apublic class. Themypkg.MyLocales class in thedate example defines a function thattests the equality of twoStrings as follows:

package mypkg;public class MyLocales {    ...    public static boolean equals( String l1, String l2 ) {        return l1.equals(l2);    }}

Then map the function name as used in the EL expression tothe defining class and function signature in a TLD (seeChapter 8, Custom Tags in JSP Pages). The followingfunctions.tld file in the date example maps theequals function to the class containingthe implementation of the functionequals and the signature of the function:

<function>    <name>equals</name>    <function-class>mypkg.MyLocales</function-class>    <function-signature>boolean equals( java.lang.String,        java.lang.String )</function-signature></function>

No two functions within a tag library can have the same name.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp