Java Server Pages表达式语言

来源:互联网 发布:linux解压缩命令 tar 编辑:程序博客网 时间:2024/06/05 03:24

对于将要使用的JSP规范的一个特点,就是JSP表达式语言。在很大程度上,它是有意简化的,并独立于JSP

JSP的早期版本中,Java代码以脚本的形式嵌入到JSP页面中,例如:

<%

MyBean bean = new MyBean();

String name = bean.getName();

out.println(name);

%>

这个脚本代码新建了一个名为MyBean的实例,获得它的Name属性,并用字符串变量name来引用它,然后输出这个字符串到页面。现在你可以来观察并思考:我可以通过JSP技术的标准操作元素(useBean)和(getProperty)来实现同样的功能。

当然,你的思考完全正确。但是在以前,你若不使用几个脚本代码,几乎不可能实现功能强大的基于JSPWeb应用程序。事实上,在JSP网页中以脚本的形式使用Java代码已经引发了许多相关性的问题。首先最明显的是,通常会由非Java程序员为系统开发用户界面。因为,一般来说,图形设计师比Java程序员更精通用户界面的开发。使用脚本代码造成的第二个问题是可维护性。因为脚本代码依赖于在页面中嵌入Java代码,所以对于使用这些脚本代码的JSP页面,其软件维护任务的复杂度大大增加了。嵌入大量的代码到系统的用户界面上,使得界面更难地变化和理解。

出于所有这些原因,JSP 2.0规范引入了表达语言(EL),脚本代码可以实现的功能,它都可以实现。这种语言比Java简单得多,它看起来非常类似脚本代码。

以下是很好的原因来解释这种相似性:

脚本代码是大多数网页制作者们早已经熟悉的内容。

• EL的灵感来自于ECMAScript,它是标准化版本的脚本代码。

事实上,JSP表达式语言的灵感来自于ECMAScriptXPath ELEL规范中详细地说明,“……参与的专家是非常不情愿的设计又一个表达式语言,他们曾经试图在不同的领域使用这些语言,但他们未能达到这个目标。

如果您一直在关注JSP JSP的标准标记库(JSTL)的发展 ,你可能就会知道,第一个表达式语言是作为JSTL的一部分被发表的。然后,ELJSTL 1.1一起被纳入JSP2.0规范。

大约在同一时间,JSF专家小组正在为JSF研制一种表达式语言。由于JSF的要求,JSF的表达式语言与JSP的表达式语言有一些不同。JSP2.1统一了两个版本,因此现在有一种表达式语言可同时用于JSPJSTLJSF

在这一章中,您将了解以下内容:

•EL的语法和用法,包括保留字,在一个页面中禁用脚本代码,以及在一个页面或一组页面中禁止解析表达式语言。

•EL运算符,包括算术运算符,关系运算符,逻辑运算符,和其他运算符。

•JavaBeansEL的使用

•EL中的隐含对象

•EL中的声明和功能使用

EL的语法和使用

在这一节中,你将学习EL的语法,在JSP的页面中如何使用它,学习语言的保留字。在您了解这些基础知识后,您就可以看如何以及为什么在在页面或一组网页中禁用ELJava脚本代码。

基本语法

无论EL在哪里使用,它总是采用一致的格式。$(expr)或者#(expr),其中,expr代表一个你想要评估的EL表达式。

EL2.1规格,$(expr)#(expr)的语法是等价的,可以互换使用。然而,当用于其他一些Java平台,企业版的API,其他API可能强制限制使用$(expr)#(expr)。具体来说,在JSP页面中,这两种形式在任何情况下都不能互换使用。因为,在一个JSP的页面,$(expr)表达式是用于立即求值,而#(expr)表达式则用于推迟求值。延迟表达式的求值用于自定义动作,您将在第67章来研究它。

这里是一个EL的简单使用。这段代码创建一个JavaBean,并且输出它的Name属性:

<jsp:useBean id="bean" class="MyBean"/>

${bean.name}

我们稍后会在“JavaBeans技术和表达式语言一节详细讨论JavaBeans的语法。

请注意,在上面的例子您使用了JSP的标准操作元素<useBean>去创建对象。这是我们推荐的方式,而不是在一个脚本代码中实例化这个对象。

文字

如在任何编程语言里一样,EL提供了一些文字供开发者去使用。文字可以是一个布尔、整数、浮点数、字符串或无效的类型。以下是每种文字类型的有效值:

布尔:truefalse

整数:下面是通过IntegerLiteral正则表达式定义的限定值:

IntegerLiteral::=['0-'9']+

这个正则表达式的意思是,09间数字的任意序列的组合。该规范还允许一个整数字面之前,加一个“-”符号,形成负的整数文字。例如,下面是有效的整数:

-102

0

21

21234

浮点:下面是通过FloatingPointLiteral定义的表达式:

 FloatingPointLiteral:: =

['’0'-'9']+'.’['0'-'9']*Exponent

 |’.‘[‘0 ' -' 9']+Exponent

|['0'-'9'] + Exponent

Exponent::=['e','E'](['+','-'])?(['0'-'9']+

这一表述更为复杂。如同整数文字,浮点文字也可以通过在文字前加一 “ -”符号来产生相反的负的浮点数。为了帮助您更好地理解,这里是一些有效的浮点数:

-1.09

-1.003

1.0E10

1 .

-10.0

0.1

字符串:任何由单引号或双引号限定的字符串。例如,"a string"'a string'两者都是有效的,但是,"as''as"是无效的。如果你想在字符串表示引号,你可以通过使用/"来表示双引号,或/'表示单引号。另外,如果该字符串是被双引号分隔的,您可以通过在字符串中不转义单引号来使用单引号,反之亦然。若想在一个字符串表示/,可以使用转义序列//

空:null

默认值和表达语言

经验表明,即使在页面中有一些简单的错误,尽可能好地提供一个介绍还是最重要的。为满足这一需求,EL不提供警告,只是默认值错误。默认值是当出现一个问题时分配到一个子表达式的纠正类型的值,同时错误被例外抛出(然后被标准JSP的错误处理程序处理)。例如,有这样一个的默认值是'无穷大'。这个值被分配到一个除以0的表达式中。例如,下面的一个EL表达式将显示一个无穷大的值,而不是引起一个错误:

$2/0

若是一个等效的Java表达式,它将抛出一个ArithmeticException 异常。

使用表达式语言

您可以在使用脚本代码的地方同样使用EL。例如:

JSP标准和自定义标签中的属性值中

在模板文本中(即是,页面的主体)

在自定义标签中使用表达式语言

JSP页面的自定义标签中使用表达式语言,可以让您指定动态属性值的自定义标记。这是一个非常强大的机制。下面的代码片段显示了如何通过使用脚本代码来动态指定属性的自定义标签:

<myTagLibrary:myTag counter="<%= 1+1 %>" />

JSP2.0规范前,要成功实现这一动态行为,你不得不使用脚本代码。正如我们讨论过,脚本代码是不简洁的,导致了可读性和可维护性的各种问题。通过使用一个EL的声明,您可以动态提供自定义标签属性的一个值。如果你想采用EL来重复以前的标记,你会看到很多代码整洁:

<myTagLibrary:myTag counter="${1+1}" />

你可以看到,1+1的值正作为一个属性传递给自定义标签counter。第6和第8章将详细地介绍创建自定义标签。

在本章的稍后,你将看到语言和JavaBeans组件、算术、比较运算在一起的更先进的应用。

JSP的模板文本使用语言表达式

现在,你已经看到EL可以用来提供自定义标签的属性值,您将学习如何在JSP的页面的主体中使用EL,最终可以产生动态内容。Listing 3-1是一个通过在JSP页面的主体中使用EL而产生动态内容的一个实例。此页面显示参数的值(通过页面)用户需要在一个文本区域输入一个新的名字,并将名字提交到另一个欢迎页面。

Listing 3-1. templateText.jsp

<html>

<head>

<title>EL and Template Text</title>

<style>

body, td {font-family:verdana;font-size:10pt;}

</style>

<head>

<body>

<h2>EL and Template Text</h2>

<table border="1">

<tr>

<td colspan="2">Hello ${param['name']}</td>

</tr>

<tr>

<form action="templateText.jsp" method="post">

<td><input type="text" name="name"></td>

<td><input type="submit"></td>

</form>

</tr>

</table>

</body>

</html>

要运行这个例子中,你需要将它部署到与JSP2.0JSP2.1兼容的环境中。这本书中的所有例子都将使用Tomcat 5.5,所以您需要如Listing 3-2创建部署描述。

Listing 3-2. web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

version="2.5">

</web-app>

以下是建立,部署和运行这个例子的完整的必要步骤:

1.    新建目录%TOMCAT_HOME%/webapps/expressionLanguage/WEB-INF.

2.    如同Listing 3-2.所示建立一个web.xml 。将其保存到webapps/expressionLanguage/WEB-INF 文件夹下。

3.    创建Listing 3-1所示JSP页面并将其保存到webapps/expressionLanguage文件夹下。

4.    开启Tomcat服务,如有需要,可以打开网络浏览器,并转到http://localhost:8080/expressionLanguage/templateText.jsp

3-1显示应该在浏览器中显示的网页。

3-1。该templateText.jsp显示用户提交的值。

正如你看到到,这个页面是一个非常简单的,个性化的问候。当网页第一次加载时,这里没有参数请求,所以问候语只有“Hello”。当Submit Query按钮按下时,参数的名称将被提交。然后JSP页面访问这个参数,并采用EL声明来打印这个问候语。在表达语言隐含对象部分,您将看到如何访问请求变量。现在,尝试在文本框中输入不同的值,并点击Submit Query按钮。


The JavaServer Pages Expression Language

One of the features of the JSP specification that you’ll be using most often is the JSP expression language, an intentionally simple language that is, to a large extent, independent from JSP.

In previous incarnations of JSP, Java code was embedded into JSP pages in the form of scriptlets, for example:

<%

MyBean bean = new MyBean();

String name = bean.getName();

out.println(name);

%>

This scriptlet creates a new instance of a class called MyBean, gets its name property, assigns this to a string variable, and then outputs this string to the page. Now you might be looking at this and thinking, “I can achieve the same thing by using the JSP standard actions (<useBean> and <getProperty>).”

Although this is certainly true, it was previously extremely hard to write a function-rich JSP-based web application without using a number of scriptlets within your pages. In fact,there are many problems associated with using Java code in the form of scriptlets in JSP pages.The first and most obvious of these is that it’s very common for non-Java programmers to create the user interface for a system. This is because graphic designers are generally better than

Java programmers at creating functional user interfaces. The second problem caused by the use of scriptlets is that of maintainability. Embedding large amounts of code into the user interface of a system makes the interface much harder to change and understand.

For all of these reasons, the JSP 2.0 specification introduced an expression language (EL) that can do pretty much everything that scriptlets can do. This language is far simpler to understand than Java and looks very similar to JavaScript. The following are good reasons for this similarity:

• JavaScript is something that most page authors are already familiar with.

• The EL is inspired by ECMAScript, which is the standardized version of JavaScript.

In fact, both ECMAScript and the XPath EL inspired the JSP EL. The EL specification states, “. . . the experts involved were very reluctant to design yet another expression language and tried to use each of these languages, but they fell short in different areas.”

If you’ve been following the progress of JSP, and the JSP Standard Tag Library (JSTL), you’re probably aware that the first expression language was released as part of the JSTL. The EL was then incorporated into the JSP 2.0 specification with JSTL 1.1.

At around the same time, the JavaServer Faces (JSF) expert group was developing an expression language for JSF. Because of JSF requirements, the JSF expression language had some differences from the JSP expression language. JSP 2.1 unifies the two versions so that there is a single expression language used for JSP, JSTL, and JSF.

In this chapter, you’ll learn the following:

• The syntax and usage of the EL, including reserved words, disabling scriptlets in a page,

and disabling the evaluation of the EL on a page or set of pages

• The operators within the EL, including arithmetic operators, comparison operators,

logical operators, and other operators

• The use of JavaBeans with the EL

• The implicit objects within the EL

• The declaration and use of functions in the EL

The Syntax and Use of the Expression Language

In this section, you’ll look at the syntax of the EL, see how to use it on a JSP page, and learn the reserved words of the language. After you’ve looked at the basics, you’ll move on to look at how and why you might disable the EL and Java scriptlets within a page or set of pages.

Basic Syntax

No matter where the EL is used, it’s always invoked in a consistent manner, via the construct ${expr} or #{expr}, where expr is the EL expression that you wish to have evaluated.

In the EL 2.1 specification, the syntax of ${expr} and #{expr} are equivalent and can be used interchangeably. However, when used with some other Java Platform, Enterprise Edition API, the other API may enforce restrictions on the use of ${expr} and #{expr}. Specifically, when used with JSP pages, the two forms cannot be used interchangeably. Within a JSP page,${expr} is used for expressions that are evaluated immediately, whereas #{expr} is used for expressions for which evaluation is deferred. Deferred expressions are used with custom actions, which you will look at in Chapters 6 and 7.

A simple use of the EL is shown here. This piece of code creates a JavaBean and outputs its name property:

<jsp:useBean id="bean" class="MyBean"/>

${bean.name}

We’ll discuss the detailed syntax of JavaBeans later in the “JavaBeans and the Expression Language” section.

Note that in the previous example you used the <useBean> standard action to create the object. This is the recommended way to do this, rather than instantiating the object in a scriptlet.

Literals

Just as in any programming language, the EL provides several literals for developers to use. A literal can be of a Boolean, integer, floating point, string, or null type. The following are valid values for each literal type:

Boolean: true or false.

Integer: This is limited to values defined by the IntegerLiteral regular expression as follows:

IntegerLiteral ::= ['0'-'9']+

This regular expression says that an integer is any sequence of digits using the digits from 0 to 9. The specification also allows an integer literal to be preceded by a unary “-” symbol to form negative integer literals. For example, the following are valid integers:

-102

0

21

21234

Floating point: This is defined by the following FloatingPointLiteral expression:

FloatingPointLiteral ::= ([''0'-'9'])+ '.' (['0'-'9'])* Exponent?

| '.' (['0'-'9'])+ Exponent?

| (['0'-'9'])+ Exponent?

Exponent ::= ['e','E'] (['+','-'])? (['0'-'9'])+

This expression is more complex. As with integer literals, a floating-point literal can be preceded by a unary “-” symbol to produce negative floating-point literals. To help you understand this, here are some valid floating-point literals:

-1.09

-1.003

1.0E10

1.

-10.0

0.1

String: A string is any sequence of characters delimited with either single or double quotes. For example, "a string" and 'a string' are both valid; however, "as' and 'as" are not valid. If you want to represent quotes within a string, then you can use /" for double quotes, or /' for single quotes. Alternately, if the string is delimited by double quotes, you can use single quotes within the string without escaping the single quotes, and vice versa. To represent a / in a string, you use the escape sequence //.

Null: You can represent null by using the literal null.

Default Values and the Expression Language

Experience suggests that it’s most important to be able to provide as good a presentation as possible, even when there are simple errors in the page. To meet this requirement, the EL does not provide warnings, just “default values” and “errors.” Default values are type-correct values that are assigned to a subexpression when there is a problem, and errors are exceptions to be thrown (and then handled by the standard JSP error-handling process). An example of such a default value is 'infinity'. This value is assigned to an expression that results in a divide by zero. For example, the following piece of EL will display infinity rather than causing an error:

${2/0}

The equivalent Java expression would throw an ArithmeticException.

Using the Expression Language

You can use the EL in the same places as you would have used a scriptlet, for example:

• Within attribute values for JSP standard and custom tags

• Within template text (that is, in the body of the page)

Using the Expression Language Within Custom Tags

Using the EL within the attributes of a custom tag in a JSP page allows you to dynamically specify the attribute values for a custom tag. This is an extremely powerful mechanism. The following code snippet shows how you might dynamically specify an attribute to a custom tag by using a scriptlet:

<myTagLibrary:myTag counter="<%= 1+1 %>" />

To achieve this dynamic behavior prior to the JSP 2.0 specification, you had to use scriptlets. As we’ve discussed, scriptlets are untidy and cause all sorts of problems with readability and maintainability. By using an EL statement, you can dynamically provide the values to a custom tag’s attribute. If you were to repeat the previous tag example by using the EL, you would see that the code is much neater:

<myTagLibrary:myTag counter="${1+1}" />

You can see that the value 1+1 is being passed to the custom tag as an attribute named counter. The details of the creation of custom tags are discussed at length in Chapters 6 through 8.

You’ll look at more advanced use of the language with JavaBeans, arithmetic, and comparisons later in this chapter.

Using the Expression Language Within JSP Template Text

Now that you’ve seen how the EL can be used to provide the values of custom tag attributes,you’ll learn how you can use the EL within the body of a JSP page so that you can produce dynamic content. Listing 3-1 shows an example of a JSP page with some dynamic content generated by the EL. This page displays the value of a parameter (passed to the page) called name. The user is then given a text field in which to enter a new name, and a button to submit

the name back to the page for another greeting.

Listing 3-1. templateText.jsp

<html>

<head>

<title>EL and Template Text</title>

<style>

body, td {font-family:verdana;font-size:10pt;}

</style>

<head>

<body>

<h2>EL and Template Text</h2>

<table border="1">

<tr>

<td colspan="2">Hello ${param['name']}</td>

</tr>

<tr>

<form action="templateText.jsp" method="post">

<td><input type="text" name="name"></td>

<td><input type="submit"></td>

</form>

</tr>

</table>

</body>

</html>

To run this example, you need to deploy it into a JSP 2.0– or JSP 2.1–compliant web container.As with all examples in this book, we will be using Tomcat 5.5, so you’ll need to create the deployment descriptor shown in Listing 3-2.

Listing 3-2. web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

version="2.5">

</web-app>

Here is the complete list of steps needed to create, deploy, and run this example:

1. Create the directory %TOMCAT_HOME%/webapps/expressionLanguage/WEB-INF.

2. Create the web.xml file shown in Listing 3-2. Save it to the webapps/expressionLanguage/

WEB-INF folder.

CHAPTER 3 THE JAVASERVER PAGES EXPRESSION LANGUAGE 99

3. Create the JSP page in Listing 3-1 and save it to the webapps/expressionLanguage folder.

4. Start Tomcat, if needed, open your web browser, and go to

http://localhost:8080/expressionLanguage/templateText.jsp.

Figure 3-1 shows the page that should appear in the web browser.

Figure 3-1. The templateText.jsp displays the value submitted by the user.

As you can see, this page is a very simple, personalized greeting. When the page first loads, there will be no request parameter, so the greeting will be only the word “Hello.” When the Submit Query button is clicked, the request is submitted with the parameter name. The JSP page accesses this parameter and uses an EL statement to print the greeting. You’ll look at how the request variable is accessed later, in the "Expression-Language Implicit Objects" section. For now, try entering different values within the text box and clicking

原创粉丝点击