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.

If value-ais a Map, return value-a.get(value-b). If !value-a.containsKey(value-b), then return null.
If value-ais a Listor array, coerce value-bto intand return value-a.get(value-b)or Array.get(value-a, value-b), as appropriate. If the coercion couldn't be performed, an error is returned. If the getcall returns an IndexOutOfBoundsException, nullis returned. If the getcall returns another exception, an error is returned.
If value-ais a JavaBeans object, coerce value-bto String. If value-bis a readable property of value-a, then return the result of a getcall. If the getmethod throws an exception, an error is returned.

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:
servletContext: The context for the JSP page's servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.

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: trueand false
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), *, /and div, %and mod, -(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: The emptyoperator is a prefix operation that can be used to determine whether a value is nullor empty.
Conditional: A ? B : C. Evaluate Bor C, depending on the result of the evaluation of A.

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 named Addis null or an empty string
${pageContext.request.contextPath}
The context path
${sessionScope.cart.numberOfItems}
The value of the numberOfItemsproperty of the session-scoped attribute named cart
${param[' mycom.productId' ]}
The value of the request parameter named mycom.productId
${header["host"]}
The host
${departments[deptName]}
The value of the entry named deptNamein the departmentsmap
${requestScope['javax.servlet.
forward.servlet_path']}
The value of the request-scoped attribute named javax.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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Unified Expression Language(JUEL)是一个基于 Java 的表达式语言,它提供了一组语法规则和函数库,可以用于在 Java 应用程序中动态地计算、处理和生成字符串、数字、布尔值和对象等数据类型。以下是一些 JUEL 的使用案例: 1. 在 JSP 页面中使用 JUEL 表达式生成动态 HTML 内容: ``` <ul> <c:forEach var="item" items="${items}"> <li>${item.name} - ${item.price}</li> </c:forEach> </ul> ``` 在这个例子中,`${item.name}`和`${item.price}`是 JUEL 表达式,它们会动态地计算出每个商品的名称和价格,并将它们插入到 HTML 中。 2. 在 JSF 应用程序中使用 JUEL 表达式进行表单验证: ``` <h:inputText id="email" value="#{user.email}" required="true" validator="#{emailValidator.validate}"> <f:ajax event="blur" render="emailMessage" /> </h:inputText> <h:message id="emailMessage" for="email" /> ``` 在这个例子中,`#{user.email}`是一个 JUEL 表达式,它会动态地计算出当前用户输入的电子邮件地址,并将它存储在一个名为`email`的属性中。在这个表单中,`email`属性是一个必填字段,所以我们使用了`required="true"`属性来指定它是必填的。同时,我们还使用了一个名为`emailValidator`的验证器来检查用户输入的电子邮件地址是否合法。`emailValidator`是一个包含了验证逻辑的 Java 类,它会在用户提交表单时被调用。 3. 在 Java 应用程序中使用 JUEL 表达式进行动态计算: ``` ExpressionFactory factory = new ExpressionFactoryImpl(); SimpleContext context = new SimpleContext(); context.setVariable("x", factory.createValueExpression(2, int.class)); context.setVariable("y", factory.createValueExpression(3, int.class)); ValueExpression expression = factory.createValueExpression(context, "#{x + y}", int.class); int result = (int) expression.getValue(context); System.out.println(result); // 输出 5 ``` 在这个例子中,我们使用了 JUEL 的 API 来创建了一个包含了表达式`${x + y}`的 JUEL 表达式。然后,我们将变量`x`和`y`绑定到了上下文中,并通过表达式的`getValue()`方法动态地计算表达式的值。最后,我们将计算出的结果输出到了控制台上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值