The JSP Expression Language

JSP 2.0 introduced the JSP Expression Language (the EL ), which is designed to make it easier for page authors to access and write logical tests. Expressions written in the EL can be embedded into static text or passed into JSP tag parameters. In both cases, the JSP engine evaluates the expression and embeds the result in the page.

Tip

Everything in this chapter up until this point will work with JSP 1.2 or JSP 2.0. The JSP EL is available only in JSP 2.0.

EL expressions begin with a $ and are enclosed by curly bracket characters. Here’s a simple example, evaluating the expression 3 > 4 (to false, of course) and also doing the sum:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <body>
    Is three greater than four? That's ${3 > 4}.
    The sum is ${3+4}, though.
  </body>
</html>

Expressions can also retrieve values from the page, request, session, and application scopes, in that order. Let’s say that you have the following Java bean:

public class Product {
    private String name = null;
    private double price = 0.0d;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public double getPrice() {
        return price;
    }
 
    public void setPrice(double price) {
        this.price = price;
    }
}

Warning

For the purpose of this example, we’ve used a double to represent the item price. We’ve done this to keep the examples short, and since we’re only displaying data it doesn’t cause any problems. However, you should not do it in a real system since floats and doubles are not accurate for certain kinds of calculations: try writing a program that multiplies 59999 by .01 and you’ll see that the answer is not quite 599.99. A better option for dealing with currency values is the java.math.BigDecimal class.

We can load the object into the request scope with a servlet like this (note that the servlet isn’t responsible for generating any HTML content, just for creating and packaging the Product object):

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
 
public class ProductServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
                            throws ServletException, IOException {
        Product product = new Product();
        product.setName("Hyperwidget");
        product.setPrice(599.99d);
        request.setAttribute("product", product);
        request.getRequestDispatcher("/product.jsp")
                    .forward(request, response);
    }
}

Now that the object is in the request scope, we can access it via the EL within the product.jsp page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head><title>Product Description</title></head>
  <body>
    <h1>${product.name}</h1>
    Price: $${product.price}
  </body>
</html>

The only trick here is that we included two $ characters before {price}: one to display to the user and one to indicate the start of the expression.

All of the built-in objects described in Table 4-2 are available within the EL. For instance, to display the application context page, you can use the expression ${pageContext.request.contextPath}, which pulls the HttpServletRequest object from the PageContext object and evaluates the contextPath bean property.

The EL also allows retrieval of values from maps using the following syntax:

mapname['key']

Using the built-in param convenience object (which contains the form parameters for the current request), the standard “Hello, Joe” application looks like this:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head><title>Generic Seasonal Greetings!</title></head>
  <body>Hello, ${param['name']}!</body>
</html>

Accessing this JSP via the URI http:///context/hello.jsp?name=Joe provides an appropriate greeting to Joe.

Using the EL with Tags

JSP EL expressions can also be used with JSP tag attributes. Simply replace the tag literal with the EL expression. For example, we can use the <c:if> tag (which we’ll look at a little more in the next section) along with an EL expression to display special shipping information if the cost of an item on our product page is more than, say, $400:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
    prefix="c" %>
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head><title>Product Description</title></head>
  <body>
    <h1>${product.name}</h1>
    Price: $${product.price}
 
    <c:if test="${product.price > 400}">
        <br/><font color="red">Eligible for Saver Shipping!</font>
    </c:if>
  </body>
</html>

Of course, we really shouldn’t have the logic for Saver Shipping eligibility embedded in the JSP itself. For more information on techniques for abstracting business logic away from content, see the chapter on Struts (Chapter 19), the chapter on JavaServer Faces (Chapter 5), or the book J2EE Design Patterns by William Crawford and Jonathan Kaplan(O’Reilly).

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.