`
o_o_0
  • 浏览: 17937 次
  • 性别: Icon_minigender_1
  • 来自: 济南
文章分类
社区版块
存档分类
最新评论

Expression Language

 
阅读更多

Expression Language

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as${name}for a simple variable or${name.foo.bar}for a nested property.

Thetestattribute of the following conditional tag is supplied with an EL expression that compares the number of items in the session-scoped bean namedcartwith 0:

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

The JSP expression evaluator is responsible for handling EL expressions, which are enclosed by the${ }characters and can include literals. Here's an example:

<c:if test="${bean1.a < 3}" >
...
</c:if> 

Any value that does not begin with${is treated as a literal and is parsed to the expected type using thePropertyEditorfor the type:

<c:if test="true" >
...
</c:if> 

Literal values that contain the${characters must be escaped as follows:

<mytags:example attr1="an expression is ${'${'}true}" /> 

Deactivating Expression Evaluation

Because the pattern that identifies EL expressions--${ }--was not reserved in the JSP specifications before JSP 2.0, there may be applications where such a pattern is intended to pass through verbatim. To prevent the pattern from being evaluated, you can deactivate EL evaluation.

To deactivate the evaluation of EL expressions, you specify theisELIgnoredattribute of thepagedirective:

<%@ page isELIgnored ="true|false" %> 

The valid values of this attribute aretrueandfalse. If it istrue, EL expressions are ignored when they appear in static text or tag attributes. If it isfalse, EL expressions are evaluated by the container.

The default value varies depending on the version of the web application deployment descriptor. The default mode for JSP pages delivered using a Servlet 2.3 or earlier descriptor is to ignore EL expressions; this provides backward compatibility. The default mode for JSP pages delivered with a Servlet 2.4 descriptor is to evaluate EL expressions; this automatically provides the default that most applications want. You can also deactivate EL expression evaluation for a group of JSP pages (seeDeactivating EL Expression Evaluation).

Using Expressions

EL expressions can be used:

  • 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 inserted into the current output. If the static text appears in a tag body, note that an expressionwill notbe evaluated if the body is declared to betagdependent(seebody-content Attribute).

There are three ways to set a tag attribute value:

  • With a single expression construct:
  • <some:tag value="${expr}"/>

    The expression is 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}"/>

    The expressions are evaluated from left to right. Each expression is coerced to aStringand then concatenated with any intervening text. The resultingStringis then coerced to the attribute's expected type.

  • With text only:
  • <some:tag value="sometext"/>

    In this case, the attribute'sStringvalue is coerced to the attribute's expected type.

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

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

See section JSP2.8 of theJSP 2.0 specificationfor the complete type conversion rules.

Variables

The web container evaluates a variable that appears in an expression by looking up its value according to the behavior ofPageContext.findAttribute(String). For example, when evaluating the expression${product}, the container will look forproductin the page, request, session, and application scopes and will return its value. Ifproductis not found,nullis returned. A variable that matches one of the implicit objects described inImplicit Objectswill return that implicit object instead of the variable's value.

Properties of variables are accessed using the.operator and can be nested arbitrarily.

The JSP expression language unifies the treatment of the.and[]operators.expr-a.identifier-bis equivalent to expr-a["identifier-b"]; that is, the expressionexpr-bis used to construct a literal whose value is the identifier, and then the[]operator is used with that value.

To evaluateexpr-a[expr-b], evaluateexpr-aintovalue-aand evaluateexpr-bintovalue-b. If eithervalue-aorvalue-bis null, returnnull.

  • Ifvalue-ais aMap, returnvalue-a.get(value-b). If!value-a.containsKey(value-b), then returnnull.
  • Ifvalue-ais aListor array, coercevalue-btointand returnvalue-a.get(value-b)orArray.get(value-a, value-b), as appropriate. If the coercion couldn't be performed, an error is returned. If thegetcall returns anIndexOutOfBoundsException,nullis returned. If thegetcall returns another exception, an error is returned.
  • Ifvalue-ais a JavaBeans object, coercevalue-btoString. Ifvalue-bis a readable property ofvalue-a, then return the result of agetcall. If thegetmethod throws an exception, an error is returned.

Implicit Objects

The JSP expression language defines a set of implicit objects:

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

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

Literals

The JSP expression language defines the following literals:

  • Boolean:trueandfalse
  • 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

Operators

In addition to the.and[]operators discussed inVariables, the JSP expression language provides the following operators:

  • 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: Theemptyoperator is a prefix operation that can be used to determine whether a value isnullor empty.
  • Conditional:A ? B : C. EvaluateBorC, depending on the result of the evaluation ofA.

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

  • [] .
  • ()- 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 not be used as identifiers.

andeqgttrueinstanceof
ornelefalseempty
notltgenulldivmod 

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

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

Table 12-2 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}
True if the request parameter namedAddis null or an empty string
${pageContext.request.contextPath}
The context path
${sessionScope.cart.numberOfItems}
The value of thenumberOfItemsproperty of the session-scoped attribute namedcart
${param['mycom.productId']}
The value of the request parameter namedmycom.productId
${header["host"]}
The host
${departments[deptName]}
The value of the entry nameddeptNamein thedepartmentsmap
${requestScope['javax.servlet.
forward.servlet_path']}
The value of the request-scoped attribute namedjavax.servlet.
forward.servlet_path

Functions

The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags (SeeUsing Custom Tagsand Chapter15).

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 the function invocation with the prefix declared in the directive.

For example, the date example pageindex.jspimports the/functionslibrary and invokes the functionequalsin an expression:

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

Defining Functions

To define a function you program it as a public static method in a public class. Themypkg.MyLocalesclass in thedateexample defines a function that tests the equality of twoStrings as follows:

package mypkg;
public class MyLocales {

...
public static boolean equals( String l1, String l2 ) {
return l1.equals(l2);
}
} 

Then you map the function name as used in the EL expression to the defining class and function signature in a TLD. The followingfunctions.tldfile in the date example maps theequalsfunction to the class containing the implementation of the functionequalsand 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> 

A tag library can have only onefunctionelement that has any givennameelement.

分享到:
评论

相关推荐

    Expression Language 3.0新特性

    Expression Language(EL)是Java EE平台中的一个关键组件,它用于在JSP、JSF等Web应用程序中方便地访问和操作服务器端的数据。EL 3.0是该语言的一个重大更新,引入了许多新特性和改进,提升了开发人员的效率和代码...

    EL(Expression Language).doc

    EL全名Expression Language EL 语法结构: ${ session.user.sex};所有EL都是以${为起始以}为结尾的; 上述语句等同于User user = (User)session.getAttribute(“user”);String sex=user.getSex(); 即在session中...

    Spring Expression Language

    **Spring Expression Language (SpEL)** 是Spring框架中的一个强大特性,它提供了一种在运行时查询和操作对象图的表达式语言。SpEL允许在应用程序中动态地访问和修改对象,使得开发人员能够灵活地编写代码,而无需硬...

    expression-language:ExpressionLanguage组件提供了一个可以编译和评估表达式的引擎。

    ExpressionLanguage组件是Symfony框架中的一个重要组成部分,专门设计用于处理和执行表达式。这个组件的核心功能是提供一个强大的、可编译的表达式语言引擎,它允许开发者在代码中动态地构造和评估各种表达式,而...

    EL(Expression Language)表达式(详解)

    EL 表达式是用于替代 JSP 页面中复杂的 scriptlet 代码的,以美元符号 "$" 开头(JSP 2.1 之后也可以使用 "#" 开头),类似 ${expression} 这样的代码行。EL 表达式在 JSP 的静态文本中使用时相当于 scriptlet ...

    Java Unified Expression Language.zip

    Java Unified Expression Language(EL)是Java EE平台中的一个重要组成部分,用于在JSP、JSF等Web应用程序中简洁、高效地表达动态内容。EL提供了一种简单的方式来访问JavaBeans或者其他Java对象的属性,使得开发者...

    Mule3.6 Expression Language By 火花

    #### 一、Mule Expression Language(MEL)概述 Mule Expression Language (MEL) 是一种轻量级且专门针对 Mule ESB 设计的表达式语言。它允许开发者访问和评估 Mule 消息中的负载、属性和变量等数据。MEL 在几乎...

    Laravel开发-laravel-expression-language

    "laravel-expression-language-master"这个文件名可能是指一个包含了源代码的仓库,可能包含了`laravel-expression-language`组件的实现细节、示例代码、测试用例以及相关文档。通过研究这个项目,开发者可以深入...

    Expression-Language

    标题:"Expression-Language" 描述:"Expression-Language EL EL EL" 知识点详解: ### 表达式语言(EL)概览 表达式语言(Expression Language,简称EL)是Java Server Pages(JSP)2.0规范中引入的一种功能...

    EL(Expression Language)表达式

    EL(Expression Language)表达式是JavaServer Pages (JSP)技术中的一个重要组成部分,它用于简化JSP页面中的数据访问和处理。EL表达式通常用`${ }`括起来,旨在替代复杂的Java脚本,使得HTML和JSP标签的交互更加...

    expression_language-2_2-mrel-spec

    ### 表达式语言(Expression Language)概述 表达式语言(Expression Language,简称EL)是为满足Web应用程序中表示层的需求而设计的一种简单语言。它由Sun Microsystems开发,并作为JavaServer Pages (JSP) 规范的...

    JSP语法_Implicit_ExpressionLanguage_JSTL.pdf

    4. **EL Elements**:即Expression Language(表达式语言),它是JSP 2.0新增的功能,用于简化页面中的表达式书写,允许开发者更简洁地访问JavaBean属性。 #### 三、批注(Comments) 在JSP中,有两种类型的批注,...

    jsp Expression Language

    **JSP Expression Language (EL)** 是JavaServer Pages(JSP)技术的一个重要组成部分,它提供了一种简洁的方式来在JSP页面中嵌入Java表达式,用于动态地输出数据。EL的引入大大简化了JSP页面的编写,使得开发者能够...

    Expression Language Specification

    从给定文件信息来看,标题和描述部分明确指出,这是一个关于“表达式语言规范(Expression Language Specification)”的文档,具体版本为3.0,并且是最终发布的版本。标题和描述中所提及的知识点如下: 1. **规范...

    基于AWEL和Agent的人工智能原生数据应用程序开发框架

    基于AWEL(Agentic Workflow Expression Language)和Agent的人工智能原生数据应用程序开发框架是实现高效、智能化解决方案的关键工具。这种框架允许开发者构建能够自主学习、适应环境变化并执行复杂任务的智能系统...

    jsp EL 2.1技术文档

    **JavaServer™ Pages Expression Language (EL)**,即JSP表达式语言,是JSP规范的一部分,用于简化页面中的数据访问过程。EL 2.1版本作为EL语言的最新版本之一,为开发者提供了更强大的功能和更灵活的数据访问机制...

    EL标签的jar文件

    EL(Expression Language)标签是JavaServer Pages (JSP) 技术的一部分,它提供了一种简单的方式来访问和操作JavaBeans组件中的属性。EL表达式语言是JSP 2.0及更高版本中引入的一种强大而灵活的数据绑定工具,用于...

    RSBK_ExpressionLanguage_JSF

    在IT行业中,`RSBK_ExpressionLanguage_JSF`这一主题主要涉及到两个核心技术:Expression Language(EL)和JavaServer Faces(JSF)。这两个技术是构建基于Java的Web应用程序的关键组件,尤其是那些采用Model-View-...

Global site tag (gtag.js) - Google Analytics