Home > Articles > Programming > Java

📄 Contents

  1. The Standard Actions
  2. The JSP Expression Language (EL)
  3. Summary
This chapter is from the book

The JSP Expression Language (EL)

The remainder of this chapter will discuss the JSP expression language. The expression language has been developed by two expert groups at the Java Community Process. One is the JSP Standard Tag Library expert group, and the other is the JSP 2.0 expert group. The reason for the involvement of both groups becomes clear when you realize that the EL is designed to be used both within JSP tags, and also in line within JavaServer Pages directly. In fact, the EL is part of the JSP2.0 specification as opposed to the JSTL 1.1 specification.

The following syntax identifies EL expressions within pages.

${ EL expression }

When used within the attributes of tags from the JSTL, for example, you end up with JSP code that looks like this:

<prefix:tag attribute="${EL Expression}" />

When used directly within pages, you could get code like this:

<body bgcolor="${EL Expression}">

Listing 3.7 shows a basic JSP that is using the expression language directly in the page.

Listing 3.7 usingEL.jsp

<!-- be aware that this listing will not work
in Tomcat 4.1, or any other JSP 1.2 container -->
<html>
<head>
<title>Expression Language Examples</title>
<%
 // set up a page context parameter for use later in the page
 // normally this would have been set within the context of
 // an application
 pageContext.setAttribute("pageColor", "yellow");
%>

</head>
<body bgcolor="${pageScope.pageColor}">

<h1>Welcome to the ${param.department} Department</h1>

Here are some basic comparisons:
<p>
Is 1 less than 2? ${1<2} <br>
Does 5 equal 5? ${5==5} <br>
Is 6 greater than 7? ${6 gt 7}<br>

<p>Now for some math:<br>
6 + 7 = ${6+7}<br>
8 x 9 = ${8*9}<br>


<hr>You appear to be using the following browser:
${header["user-agent"]}

</body>
</html>

The output of Listing 3.7 with the JSP 2.0 early access preview version of Tomcat appeared as shown in Figure 3.4.

Figure 3.4Figure 3.4 The output from usingEL.jsp in a browser.

Listing 3.7 will be referred to as we progress through the chapter. So, what does the EL look like? It draws its syntax from two other scripting languages: XPath and ECMAScript. XPath is used in XML applications and is discussed in Chapter 11, "Transforming XML Using XSLT and XSLFO." ECMAScript is mainly used as a client-side scripting language in Web applications, and is also commonly used in the development of Microsoft Active Server Pages.

NOTE

ECMAScript was developed within the context of the European Computer Manufacturers Association. It is essentially a standardization of Netscape's JavaScript, which has been widely used as a client-side scripting language in both Internet Explorer (implemented as JScript) and Netscape browsers.

The EL has the following features:

  • It has a set of implicit objects available to it.

  • It has a comprehensive set of operators.

  • It can access collections and nested properties in an intuitive way.

  • It has a selection of extensible functions mapping to static methods in Java classes.

EL Literal Types

The expression language has the following basic types that can be used for literal values:

  • String—This is a value defined within double or single quotes.

  • Boolean—Like Java, this type has only the possible values of true and false.

  • IntegerLiteral—This type represents signed integral numbers. It is implemented as a Java long.

  • FloatingPointLiteral—This type represents floating-point numbers.

  • NullLiteral—This is the same as the Java null. The literal value for this is null.

The EL Operators

The EL has a comprehensive set of operators as you might expect. We will explore these in this section. As you'll see, many of them are the same as those found in the Java Programming language. The main difference, however, is that for many operators there is a textual equivalent. The most commonly used operators are discussed here; for a complete list visit the JSP 2.0 specification at http://www.jcp.org/jsr/detail/152.jsp.

The Arithmetic Operators

There are the expected operators here: +, -, *, /, %. You can also use the following for the / and % operators: div and mod. You can see examples of these being used in Listing 13.7:

<p>Now for some math:<br>
6 + 7 = ${6+7}<br>
8 x 9 = ${8*9}<br>

The Relational Operators

The relational operators are shown in Table 3.2.

Table 3.2 The Relational Operators

Symbol Version

Text Version

==

eq

!=

ne

<

lt

>

gt

>=

ge

<=

le


Notice that they all have a text version in addition to the more familiar symbol version. These are also used in Listing 13.7:

Here are some basic comparisons:

<p>
Is 1 less than 2? ${1<2} <br>
Does 5 equal 5? ${5==5} <br>
Is 6 greater than 7? ${6 gt 7}<br>

The Logical Operators

The logical operators are the same as the Java Programming Language, but they also have their textual equivalents within the EL. They are shown in Table 3.3.

Table 3.3 The Logical Operators

Symbol Version

Text Version

&&

and

||

or

!

not


The empty Operator

The empty operator allows you to test the following:

  • Object references to see if they are null.

  • Strings to see if they are empty.

  • Arrays to see if they are empty.

  • Lists to see if they are empty.

  • Maps to see if they are empty.

You use the operator in the following way:

empty variableName

If any of the above conditions are met, then the operator returns true.

Operator Precedence

The operator precedence works from the highest precedence through to the lowest precedence, and then left to right - In other words, the same as the Java programming language. As with any other programming language, you can affect this precedence with the use of parentheses ().

The operator precedence table as defined by the JSP 2.0 specification is shown below in Table 3.4:

Table 3.4 The Operator Precedence Table for the EL

[] .

()

-(unary) not ! empty

* / div % mod

+ - (binary)

<> <= >= lt gt le ge

== !- eq ne

&& and

|| or


Accessing Objects and Collections

In the Java Programming Language, objects and their properties are accessed using get and set methods. This is because of encapsulation, and it is not considered good practice to access object properties directly.

So, for example, if there were a hierarchy of objects such as a bookstore, with a book, and the book had a chapter, the code would be something like

getBookStore().getBook().getChapter("Ch03FurtherJSP");

This can look quite messy, and although hiding the variables provides encapsulation, it is not clear to read, especially within JSPs in code like this:

<%= getBookStore().getBook().getChapter("Ch03FurtherJSP") %>

If this were a scripting language such as ECMAScript, it would be something like

bookStore.book.chapters.Ch03FurtherJSP

If you are familiar with ECMAScript, you will have seen how objects can be accessed in a variety of ways in that language. This is also the case in the EL. So, taking our basic chapter example one step further, using the EL, you can access this chapter object in the following ways:

bookStore.book.chapters.Ch03FurtherJSP
bookstore["book"].chapters.Ch03FurtherJSP
bookstore['book'].chapters["Ch03FurtherJSP"]

Essentially, what we are saying here is that there are two operators that can be used to enable you to access objects. One is the dot operator (.), and the other is the [] brackets. When using the brackets, you can place the name of a subproperty as a String in either double or single quotes within them, as shown. Using the dot enables you to step down through properties and the various subproperties.

CAUTION

In ECMAScript, you can also access objects by putting an index number in the square brackets. This is not possible in the EL unless the property is a collection of some kind.

This mechanism for accessing objects makes the development of JSPs substantially easier. This is especially true for Web designers, who will most probably already be experienced in the ECMAScript object access mechanisms, which are now available to the JSP developer.

The previous caution mentions that the use of the square brackets is also used to access collections. The EL can handle the various Java collection types, and it uses a generic syntax for accessing a collection, regardless of the actual collection implementation. So, the collection could be an array, a List, a Vector, and so on, but the syntax would be the same. Collections are accessed in a similar way to how an array would be accessed in the Java Programming Language; in other words, an index is placed within the square brackets. So, in the earlier simple example, if the chapters were stored as a List rather than individual named properties, you could access Chapter 3 in the following way:

bookStore.book.chapters[2]

If the collection were a Map, instead of an index number being placed within the square brackets, a key would be used:

bookStore.book.chapters["Ch03FurtherJSP"]

The access of objects from the EL is illustrated by the following worked example, starting with the JSP shown in Listing 3.8.

Listing 3.8 ELAccessingObjects.jsp

<!-- be aware that this listing will not work
in Tomcat 4.1, or any other container that does
not support the use of the expression language outside
of tags -->
<html>
<head>
<title>Expression Language Accessing Objects</title>

<p>Now lets use some objects. You will see more on the bean standard actions
in chapter 6. But for now, remember that here useBean instantiates beans
and setProperty sets the properties of beans.

<%-- create a single Person object --%>
<jsp:useBean id="man" class="com.conygre.Person">
<jsp:setProperty name="man" property="name" value="Nick"/>
<jsp:setProperty name="man" property="password" value="pass"/>
</jsp:useBean>

<p>Now we will use the expression language to access the properties.
The person is called ${man.name}, and the password is ${man.password}.

Now a list and a map is created as properties of the GroupPeople class.

<%-- create a GroupPeople object that contains a List and a Map --%>
<jsp:useBean id="group" class="com.conygre.GroupPeople"/>

The map is accessible using the following syntax:<br>
The first author is called ${group.mapPeople["authorA"]},
and the second author is called ${group.mapPeople["authorB"]}.

<p>The List is accessible also, but using the following syntax:<br>
The first author is called ${group.listPeople[0]},
and the second author is called ${group.listPeople[1]}.

</body>
</html>

In Listing 3.8, you can see the JavaBean related standard actions being used to set up two beans. One is a Person bean, which is based upon the Java class shown in Listing 3.9, and the other is a GroupPeople bean, shown in Listing 3.10.

Listing 3.9 Person.java

package com.conygre;
public class Person {

 private String name;
 private String password;

 public String getName(){
  return name;
 }
 public void setName(String s){
  name = s;
 }
 public String getPassword(){
   return password;
 }
 public void setPassword(String s){
   password = s;
 }
}

Listing 3.10 GroupPeople.java

package com.conygre;
import java.util.*;
public class GroupPeople {

 private List listPeople;
 private Map mapPeople;

 public GroupPeople()
 {
  listPeople = new Vector();
  listPeople.add("Nick");
  listPeople.add("Mark");
  mapPeople=new HashMap();
  mapPeople.put("authorA", "Nick");
  mapPeople.put("authorB", "Mark");
 }


 public List getListPeople(){
  return listPeople;
 }

 public void setListPeople(List s){
  listPeople = s;
 }

 public Map getMapPeople(){
   return mapPeople;
 }

 public void setMapPeople(Map s){
   mapPeople = s;
 }
}

The crucial lines within the JSP of Listing 3.8 are the ones that access bean properties using the EL. They are shown below:

The person is called ${man.name}, and the password is ${man.password}.
. . .
The map is accessible using the following syntax:<br>
The first author is called ${group.mapPeople["authorA"]},
and the second author is called ${group.mapPeople["authorB"]}.

<p>The List is accessible also, but using the following syntax:<br>
The first author is called ${group.listPeople[0]},
and the second author is called ${group.listPeople[1]}.

The first line in this snippet is accessing the Person instance with the id of man. It is accessing the name and password properties directly.

The remainder of this snippet demonstrates how maps and lists are accessed. The GroupPeople bean has a Map property and a List property set up with some Strings as content, as shown in Listing 3.10. The GroupPeople object id is set up as group. Therefore the code accesses the properties listPeople and mapPeople as you would expect. Notice that the List values are accessed by their indices, and the Map values are accessed by their key names.

The EL Implicit Objects

In the previous chapter, you were exposed to the implicit objects available to the JSP developer for use within your pages. The Expression Language also provides a number of implicit objects that can be used directly from within EL code. Table 3.5 lists these objects and what they can be used for.

Table 3.5 The EL Implicit Objects

Name

Description

pageContext

This is the page context object,. The the same object that is available as a JSP-implicit object. This was discussed in detail in Chapter 2.

pageScope

In the very last section of Chapter 1, the idea of scope was introduced. Page-scoped attributes can be accessed by name using this variable. This is because the variable is a Map. Here is an example of accessing a page-scoped object that we have called pageColor:

<body bgcolor="${pageScope.pageColor}"> or

<body bgcolor="${pageScope['pageColor']}">

This example can be seen in Listing 3.11.

requestScope

The requestScope is also a Map object, but it contains all the request-scoped attributes. It can be used in the same way as the pageScope.

param

The param object is another Map that contains any request parameters normally accessed using the request.getParameter(String paramName) method. This could be used as a more convenient mechanism for accessing parameters. The following fragment shown here could be rewritten from

<h1><%=request.getParameter("department") %>

Department</h1>

To to a more simple

<h1> ${param.department} Department</h1>

This example can be seen in Listing 3.7.

paramValues

This object represents the result of the call to request.getParameterValues(String paramName). This method returns an array of parameter values based on a particular parameter name. The following would return all the values of a parameter called favoriteColors.

${paramValues.favoriteColors}

header

This implicit variable contains a Map of all the headers along with their values. It returns the result of the method request.getHeader(String headerName).

The following example accesses the user agent, which details the client browser:

${header["user-agent"]}

This is visible in Listing 3.7.

headerValues

This object represents the result of the call to request.getHeaders(String headerName). This method returns an array of header values based on a particular header name.

sessionScope

The sessionScope is a Map object that contains all the session-scoped attributes. It can be used in the same way as pageScope.

cookie

This variable provides access to the Cookies array that is available to JSP via the request.getCookies() method. Cookies are discussed in Chapter 8, "Session Tracking Using JSP."

applicationScope

The applicationScope is a Map object that contains all the application-scoped attributes. It can be used in the same way as pageScope.

initParam

This variable gives access to all the initialization parameters that may have been passed to the JSP when its corresponding servlet was initialized.


Reserved Words

There are also a number of reserved words for the EL. Many of these are textual versions of the operators listed in Table 3.6. Others are words that currently have no use, but have been reserved for future use. They are all shown in Table 3.7.

Table 3.6 The Reserved Words

lt

ge

le

eq

and

true

ne

or

false

gt

not

null

instanceof

empty

div

mod

 

 


Expression Language Functions

The expression language also provides a number of functions, associated with string manipulation and for working with collections. These are shown in Table 3.7. Note that this list was taken from the JSTL 1.1 maintenance review proposals, and it is possible that this list is not the exact final list of functions.

Table 3.7 Expression Language Functions

Function

Description

boolean contains(string,

Returns true if the specified String contains the

substring)

sequence of characters in the specified substring.

boolean containsIgnoreCase(string, substring)

Returns true if the specified String contains the sequence of characters in the specified substring, but not taking account of case.

boolean endsWith(string, suffix)

Returns true if the string ends with the supplied string suffix.

String escapeXml(string)

Escapes any XML sensitive characters in supplied string (&, <, >, ', ") with the predefined XML entity equivalents and returns the result as a String. See Chapter 10, "Utilising XML from JSP" for more information on XML.

int indexOf(string, substring)

Returns the index within this string of the first occurrence of the specified substring.

String join(collection, separator)

This method takes in a collection, and concatenates the values together in a String, using the supplied separator.

int length(collection)

Returns the length of a Collection as an int.

String replace(inputString, beforeSubstring, afterSubstring)

Replaces the characters in a substring of the input string with the additional characters specified.

String[] split(string, separator)

Takes in a String, and converts the contents into a String array, with each new array entry beginning when the separator character is found.

boolean startsWith(string, prefix)

Queries a String to see if it starts with the supplied prefix.

String substring(string, beginIndex, endIndex)

Returns a substring from a string based upon the supplied beginning and end indexes.

String substringAfter(string, substring)

Returns a substring from a supplied string. The substring is the contents of the supplied string located after the supplied substring.

String substringBefore(string, substring)

Returns a substring from a supplied string. The substring is the contents of the supplied string located before the supplied substring.

String toLowerCase(string)

Converts a supplied string to upper case.

String toUpperCase(string)

Converts a supplied string to lower case.

String trim(string)

Returns a copy of the supplied string with any leading and trailing white space removed.


In addition to the supplied functions, you can also create your own. This is done by exposing static functions present in Java classes. For example, if a static method had the following signature:

public static String returnNewString(String oldString)

You would be able to invoke it from a page using the following style of EL construct:

${myTagLibrary:returnNewString("the old string value")}

Any parameters that the method takes are passed in as a comma-separated list. How these functions are set up is discussed in Chapter 9, "Developing Custom Tag Libraries."

Controlling Expression Language and Scriptlet Use

It is possible to deactivate the processing of EL elements within a JSP with the use of the following entry in the page directive. This might be necessary if aspects of the content of a page actually contained output of the format ${xxx}. To deactivate the expression language, you can disable it for entire groups of pages within a web application using an entry type in web.xml that is new in JSP 2.0. The entry is of the following format:

<jsp-property-group>
 <url-pattern>*.jsp</url-pattern>
 <el-ignored>true</el-ignored>
</jsp-property-group>

The <jsp-property-group>, discussed earlier in the chapter, is an element that can be used in web.xml to configure groups of JSPs. In the above example, the expression language will be disabled for all JSP files.

Alternatively, you can disable the expression language for an individual page by setting the isELIgnored attribute of the page directive.

<%@page isELIgnored="false" %>

Using the <jsp-property-group> element, you can also disable scripting elements. The following is an example of a jsp-property-group that does this:

<jsp-property-group>
 <url-pattern>*.jsp</url-pattern>
 <scripting-invalid>true</scripting-invalid>
</jsp-property-group>

This means that using these <jsp-property-group> elements, you can effectively enforce the use of the expression language instead of scriptlets using the two <jsp-property-group> elements shown above. This will enforce the separation of the Java from the JSPs.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020