Previous
Index

Next

7.4) EL and the JSTL

Using Expression Language (EL)

The expression language (EL from now on) is a new feature of JSP and was introduced with the JSP 2.0 specification. It's purpose was to help programmers write JSP pages with fewer or no scriptlets. This allows the programmer to use code that looks even more like tags than code. It's important to note that EL does not try to be particularly like Java but it is relatively easy to understand and can help “clean up” the layout of a page by comparison with scriptlets. EL is a bit odd in that it does not use the standard angle brackets of tag systems like XML but it uses the ${content} approach to escape from the rest of the JSP content.

So the previous example could be reformatted as

<jsp:useBean id="person" type="com.examulator.Person"
class="com.examulator.Person" scope="session" />
<html>
${person.firstName}
</html>

More EL

EL can be used in many places where scriptlets would otherwise be used. They can be used to manipulate HTTP parameters via the ${param.paramName} construct. Thus given a JSP with the following code

${param.language}

And calling the page with the following query string

getlang.jsp?language=english

The string english will be displaed in the page

Attributes can be accessed in a similar way, (remember that attributes are a way of storing Java objects and are entirely different to request parameters which exist only from one HTTP call to the next).

Given that a session based attribute has been set up in the same way as the prvious example.

<html>    
    <body>
        <h2>Start Session</h2>
        <%
        String[] fruit = {"apple","orange","pear"};
        session.setAttribute("fruit_at",fruit);
        %>
    </body>
</html>

Elements of the attribute can be accessed from any page that is part of the session as follows.

 ${fruit_at[0]}

Note how this is far neater than the scriptlet version which required the use of the getAttribute method call and the cast back to the original String array type.

One of the nice things about EL is that it generally doesn't throw ugly error messages. Thus if the fruit_at attribute does not exist the EL call will be silently ignored with no null pointer message or other error.

There are some areas where EL works like you would hope but based on previous Java experience not expect. For example it will allow the wrapper objects to be used as if they were primitives, e.g. two instances of the Integer wrapper can be multiplied as if they were primitives. Take the following example where two session attributes have been initialized as follows.

  <%
        Integer height = new Integer(10);
        Integer width = new Integer(10);
        session.setAttribute("height_at",height);
        session.setAttribute("width_at",width);
  %>

These two attributes can be accessed as follows in a subsequent page within the same session as follows

${height_at * width_at}

Custom Tags

Custom tags are extensions to the JSP language in that they allow a programmer to define new features that can be used in a similar way to the built in JSP tags. Custom tags are distributed in the form of a custom tag library (typically in a jar file). Custom tags offer additional re-usable objects in a similar way to JavaBeans. They contribute towards the goal of separating the business logic from the presentation logic. There are two ways of creating custom tags, the “classic complex hard work” way and the relatively easy simple tag way. There are very few reasons for using the older classic custom tag approach so I will describe the basics of creating a simple custom tag. The following tag code will produce the standard “Hello World” output.

package com.examulator;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class TagDemo extends SimpleTagSupport {
  public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.write("Hello, world.");
  }
}

To make your custom tag available to a JSP you need to create a Tag Library Descriptor file. The following is a TLD for the TagDemo tag.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-
Page 249

jsptaglibrary_1_1.dtd">
<taglib>
    <tlibversion>1.0</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>TagDemo</shortname>
    <uri>http://www.mycompany.com/taglib</uri>
    <info>An example tag library</info>
    <tag>
        <name>TagDemo</name>
        <tagclass>com.examulator.TagDemo</tagclass>
        <body-content>empty</body-content>
        <info>Just Says Hello</info>
    </tag>
</taglib>

If you save this under your WEB-INF directory you can access your custom tag in a JSP with the following code.

<%@ taglib uri="WEB-INF/tagdemo.tld" prefix="h" %>

<html>
    <body>
        <h:TagDemo/>
    </body>
</html>

When you call this JSP page it will generate the HelloWorld output indicated within the tag. The TagDemo is a very basic demonstration of the process, in a real tag you would probably want to manipulate attributes to get information in and out of the tag. Fortunately you will probably never have to create your own tags because the JSTL covers just about everything most programmers will ever want to do.

The JSTL

Why design, program, debug and test your own tags when someone else has probably already created and made the same functionality available? I always err on the side of using code that has been widely used elsewhere as it is more likely to have been tested and debugged than anything I can produce.

The JSTL includes four libraries covering XML, fmt (formatting and internationalization and SQL for database access and the core library. I will cover the basics of the core library as if you use JSTL you will almost certainly use the core. To make JSTL available to your application you need to give it access to the appropriate libraries (jar files), which contain everything you need including the required Tag Library Descriptor files.

The following illustrates the <c:out tag displaying the classic Hello World string.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
        <c:out value="Hello World"/>
</html>

<c:forEach>

The <c:forEach tag works in a similar way to the new for loop construct introduced with JDK 1.5 (Java 5). It allows code to loop through a collection without having to explicitly set up a counter variable. The following JSP page illustrates this by using a JavaBean of type Vector which is populated via a scriptlet.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<jsp:useBean id="capitals" class="java.util.Vector" />
<html>
<head>
<title>Using the JSTL forEach tag</title>
</head>
<body>
<%
capitals.add("Australia");
capitals.add("France");
capitals.add("UK");
%>
<c:forEach var="city" items ="${capitals}" varStatus="counter">
<c:out value="${counter.count}"/>
<c:out value="${city}"/>
<br/>
</c:forEach>
</body>
</html>

The output of this page will be

1 Australia
2 France
3 UK

The <c:if tag

The <c:if tag works in a very similar way to the standard Java if control structure, with the very important difference that it does not offer an else tag.

The JSTL <c:if does not have a corresponding else tag

The following JSP code shows how it can be used to control what file is included, and also how the lack of an else construct is a significant limitation.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<head>
    <title>Using the JSTL if tag, note the lack of else</title>
</head>
<body>
 <c:if test="${param.locale == 'UK'}" >
    <jsp:include page="ukmenu.jsp" />
 </c:if>
  <c:if test="${param.locale == 'US'}" >
    <jsp:include page="usmenu.jsp" />
 </c:if>
   </body>
</html>

This code is all very fine so long as the locale param is either UK or US, but for those tiny insignificant parts of the planet that are not in those locales there will be no page included. For this type of situation you might be as well to use the chose,when and otherwise tags instead.<c:choose <c:when and <c:otherwise

The chose when and otherwise tags work in a similar way to the standard java switch/case/default construct. The following JSP page will change the output according to what value is given to the local parameter in the request string.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<head>
    <title>Using the JSTL chose,when,otherwise tags</title>
</head>
<body>
     <c:choose>
     <c:when test="${param.locale == 'UK' }">
          We spell it colour (with an extra letter u)
     </c:when>
     <c:when test="${param.locale == 'US' }">
          They  spell it color
      </c:when>
      <c:otherwise>
          No information for that locale
      </c:otherwise>
      </c:choose>          
   </body>
</html>

If the request string is neither UK or US then the output will be “No information for that locale”. If the request string is

?locale=US

it will output the US spelling of color, if it is

?locale=US

It will output the UK spelling of colour

Using EL operators with the JSTL

The EL operators can be put to good use by embedding EL within the conditional operators of the JSTL. The following example demonstrates the use of the <c:if JSTL tag along with the EL greater than operator.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<body>
<%
int[] i = {10};
request.setAttribute("age",i);
%>
<c:if test='${age[0] >1}'>
The value was greater than one
</c:if>
</html>

The EL according to Oracle

http://www.oracle.com/technology/pub/articles/cioroianu_jspapi.html

IBM article The JSTL EL

http://www-128.ibm.com/developerworks/java/library/j-jstl0211.html

Visual Web Page design with Java

The one thing missing from these technologies is the availability of What You See is What You Get (WYSIWYG) page design. This is promised via the use of Java Server Faces or JSF. I won't go into any of the details of JSF but it is worthwhile having a play with the Visual Page Design tool within NetBeans to see how Java can be used to design pages visually rather than programmatically. I'm not sure if it is the future of server side Java development but if it is it could make developers life much easier in the future.


The EL according to Oracle
http://www.oracle.com/technology/pub/articles/cioroianu_jspapi.html

IBM article The JSTL EL
http://www-128.ibm.com/developerworks/java/library/j-jstl0211.html

http://www.examulator.com/fjt



Previous
Index

Next