Tutorial: Understanding the New Features of JSP 2.0
Discuss this tutorial. Printable version (PDF).
Go to Contents page. Go to previous page. Go up a level. Go to next page.

 

 

Simple Expression Language


Sun Microsystems introduced the Servlet API, in the later half of 1997, positioning it as a powerful alternative for CGI developers who were looking around for an elegant solution that was more efficient and portable than CGI (Common Gateway Interface) programming. However, it soon became clear that the Servlet API had its own drawbacks, with developers finding the solution difficult to implement, from the perspective of code maintainability and extensibility. It is in some ways, this drawback that prompted the community to explore a solution that would allow embedding Java Code in HTML - JavaServer Pages (JSP) emerged as a result of this exploration.

It was not long before that developers realized the incomprehensibility and lack of maintainability associated with complex JSP pages that mixed presentation and business logic together. Another issue that surfaced for page authors, who could not write scriplets, was JSP's limitation in terms of standard tag sets. These limitations set the ball rolling to create JSP custom tags, leveraging on JSP's mechanism for implementing custom tags.

The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that encapsulates, as simple tags, core functionality common to many JSP applications. It eliminates the need to use JSP scriptlets
and expressions and uses a higher-level syntax for expressions. It also implements general-purpose functionality such as iteration and conditionalization, data management formatting, manipulation of XML, database access, internationalization and locale-sensitive formatting tags, and SQL tags. JSTL 1.0 introduced the concept of the EL but it was constrained to only the JSTL tags. With JSP 2.0 you can use the EL with template text and even get programmatic access via javax.servlet.jsp.el.

Following from our understanding of how JSTL fits into the picture, and the constraints associated with the JSTL expression language, we will look at one of the important nuggets of JSP 2.0 - the JSP Expression Language (EL). We will specifically cover the following:

JSP Expression language defined
Mechanisms to enable EL in scriptlesss JSP pages
Expression language Syntax
Valid Expressions in the JSP EL
Using EL Expressions

JSP Expression language defined

The Expression Language, inspired by both ECMAScript and the XPath expression languages, provides a way to simplify expressions in JSP. It is a simple language that is based on available namespace (the PageContext attributes), nested properties and accessors to collections, operators - arithmetic, relational and logical, extensible functions mapping into static methods in Java classes, and a set of implicit objects.

EL provides the ability to use run-time expressions outside JSP scripting elements. Scripting elements are the elements in a page that can be used to embed Java code in the JSP file. They are commonly used for object manipulation and performing computation that affects the generated content. JSP 2.0 adds EL expressions as a scripting element.

Scripting elements have three subforms:

  • Declaration
  • Scriptlets
  • Expressions.

    Let's look at these three subforms in code:

    <%! int i = 1; %> <% -- Declaration --%>
    <% for (int i =0; i < 10; i++) { %> <% -- Scriptlets --%>
    <jsp:expression> table.getColumn( ) </jsp:expression> <% -- Expression --%>

    With the addition of EL to the JSP toolkit, the above code can be written using a simpler syntax yet achieving the same results as the JSP elements above. Another advantage of EL expressions is its use in scriptless JSP pages that do not permit the usage of any of the above scripting element subforms. However, it must be noted that JSP pages can be written without the usage of any of the three scripting element subforms, and that the choice of whether a JSP page should be scriptless is entirely based on the requirements and needs of your application. If you want a clear seperation between your presentation and business logic, then you also have the choice to force the page to go scriptless. By enforcing scriptless pages, the dynamic behavior of JSP pages must be provided through other elements such as JavaBeans, EL expressions, Custom actions and standard tag libraries.

    Mechanisms to enable EL in scriptlesss JSP pages

    There are two mechanisms that are available to ensure that a page does not contain any scripting elements. Each of these mechanisms also provide a way to enable EL in scriptless JSP pages.

    • Using a page directive:

      When using a page directive, you can specify whether EL is enabled or not by setting the value of the isELEnabled directive to "true" or "false" respectively, as shown below:

      <%@ page isScriptingEnabled="true|false" isELEnabled="true|false"%>
    • Using an element of the deployment descriptor:

      When using an element of the deployment descriptor, you can specify whether EL is enabled or not by including the boolean value "true" or "false" in between <el-enabled> tags, as shown below:
      ...
      <jsp-config>
      <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <el-enabled>true</scripting-enabled>
      <scripting-enabled>true</scripting-enabled>
      </jsp-property-group>
      </jsp-config>
      ....

    Expression Language Syntax

    The JSP expression language allows a page author to access a bean using a simple syntax such as:

       
       ${expr}

    In the above syntax, expr stands for a valid expression. It must be noted that this expression can be mixed with static text, and may also be combined with other expressions to form larger expressions.

    Valid Expressions in the JSP EL

    Valid expressions can include literals, operators, variables (object references), and function calls. We will look at each of these valid expressions seperately:

    Literals

    The JSP Expression language defines the following literals that can be used in expressions:

    Literals Literal values

    Boolean

    true and false

    Integer

    Similar to Java. It can include any positive or negative number e.g, 24, -45, 567

    Floating Point

    Similar to Java. It can include any positive or negative floating point numbers e.g, -1.8E-45, 4.567

    String

    Any string delimited by single or double quotes. For single quotes, double quotes, and backslashes use the backslash character as an escape sequence.It must be noted that if double quotes are used around the string, the single quote need not be escaped.

    Null null

    Let us look at some examples that use Literals as valid expressions:

    ${false} <%-- evaluates to false --%>
    ${3*8)

    Operators

    The JSP expression language provides the following operators, most of which are the usual operators available in Java:

    Term Definition

    Arithmetic

    +, - (binary), *, /, div, %, mod, - (unary)

    Logical

    and, &&, or, ||, !, not

    Relational

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

    Empty

    The empty operator is a prefix operation that can be used to determine if a value is null or empty.

    Conditional A ? B : C. Evaluate B or C, depending on the result of the evaluation of A.

    Let us look at some examples that use Operators as valid expressions:

    ${ (6 * 5) + 5 } <%-- evaluates to 35 --%>
    ${empty name}

    Implicit Objects

    The JSP expression language defines a set of implicit objects, many of which are available in JSP scriplets and expressions:

    Term Definition

    pageContext

    The context for the JSP page. It can be used to access the JSP implicit objects such as request, response, session, out, servletContext etc. For example, ${pageContext.response} evaluates to the response object for the page.

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

    Term Definition

    param

    maps a request parameter name to a single String parameter value (obtained by calling ServletRequest.getParameter (String name). The getParameter (String) method returns the parameter with the given name. The expression $(param.name) is equivalent to request.getParameter (name).

    paramValues

    maps a request parameter name to an array of values (obtained by calling ServletRequest.getParameter (String name). It is very similar to the param implicit object except that it retrieves a string array rather than a single value. The expression ${paramvalues.name) is equivalent to request.getParamterValues(name).

    header

    maps a request header name to a single String header value (obtained by calling ServletRequest.getHeader(String name). The expression ${header.name} is equivalent to request.getHeader(name).

    headerValues

    maps a request header name to an array of values (obtained by calling ServletRequest.getHeaders(String)). It is very similar to the header implicit object. The expression ${headerValues.name} is equivalent to request.getHeaderValues(name).

    cookie maps cookie names to a single cookie object. A client request to the server can contain one or more cookies. The expression ${cookie.name.value} returns the value of the first cookie with the given name. If the request contains multiple cookies with the same name, then you should use the ${headerValues.name} expression.
    initParam maps a context initialization parameter name to a single value (obtained by calling ServletContext.getInitparameter(String name)).

    Outside of the above two types of implicit objects, there are also objects that allow access to the various scoped variables such as Web context, session, request, page:

    Term Definition

    pageScope

    maps page-scoped variable names to their values. For e.g., an EL expression can access an object, with a page scope in the JSP, with ${pageScope.objectName} and an attribute of the object can be accessed using ${pageScope.objectName.attributeName}.

    requestScope

    maps request-scoped variable names to their values. This object allows for access to the attributes of the request object. For e.g., an EL expression can access an object, with a request scope in the JSP, with ${requestScope.objectName} and an attribute of the object can be accessed using ${requestScope.objectName.attributeName}.

    sessionScope

    maps session-scoped variable names to their values. This object allows for access to the attributes of the session object. For example:

    <% session.put (name", "John Doe"); %>
    $sessionScope.name} <%-- evaluates to John Doe --%>
    <%= session.get("name"); %> <%-- This is an equivalent scripting expression --%>

    applicationScope

    maps application-scoped variable names to their values. This implicit object allows for access to objects with application scope.

    It must be noted that when an expression references one of these objects by name, the appropriate object is returned instead of the corresponding attribute. For example: ${pageContext} returns the PageContext object, even if there is an existing pageContext attribute containing some other value.

    Using EL Expressions

    EL expressions can be used in two situations:

    • As attribute values in standard and custom actions

    • In template text, such as HTML or non-JSP elements, in the JSP file - In this situation, the value of the expression in template text is evaluated and inserted into the current output. However, it must be noted that an expression will not be evaluated if the body of the tag is declared to be tagdependent.

    Discuss this tutorial. Printable version (PDF).
    Go to Contents page. Go to previous page. Go up a level. Go to next page.
  • E-mail this page
    Printer View Printer View
    Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy