java

JSTL Examples

JSTL Examples
(last updated: Oct 11, 2009) — print

Select font size:    8pt   9pt   10pt   11pt   12pt   14pt   16pt 

JSTL overview and setup

JSTL stands for the Java Server Pages Standard Tag Library. This library provides a set of XML-tags which provide Java programming functionality delivered by the tags along with expressions created in the unimaginatively named UnitedExpression Language, or EL. The goal of JSTL is to minimize or, if possible, eliminate actual Java code introduced through JSP.

Refer to these hyperlinks

Sun JSTL site: http://java.sun.com/products/jsp/jstl/
Docs on Sun site: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
Apache Jakarta TagLib home page: http://jakarta.apache.org/taglibs/
Docs on Computer Science server: http://www.cs.wcupa.edu/docs/tld
Download the documentation: jstl-1_1-mr2-spec-tlddoc.zip

Install into tomcat

JSTL requires two new library JAR files which are included in the tomcat distribution but not available for all applications. Prior to starting NetBeans, locate the directory:

apache-tomcat-7.0.12/webapps/examples/WEB-INF/lib/

and within it, the files:

jstl.jar  standard.jar

Simply copy these two files into:

apache-tomcat-7.0.12/lib/

If tomcat is already running in NetBeans, you need to restart it in one way or another.

Install the project

Download the JSTLexamples.zip archive. Follow the usual steps in order to install the web application JSTLexamples from existing sources. The archive contains the following files:

index.jsp project root
session-elements.jsp session elements used in EL
iteration.jsp JSTL iteration tags
display-examples.jsp examples with c: tags
bean/MyBean.java bean example with get/set properties
bean-access.jsp EL/JSTL bean usages
user-tags.jsp usage of user-defined tags
WEB-INF/MyTags.tld tag library definitions
mytaglib/MyFunctions.tld tag library functions
query-params.jsp EL access to query parameters

JSTL tags

The JSTL tags are those described in the table below. We have omitted the sql tags since we don’t plan to use SQL operations directly in JSP. Using a tag groups is effected by the addition of one of the following respective tag statements below.

c:   <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
fn:  <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
fmt: <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
xml: <%@taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

The uri identifies the tag set. The tag prefix can be set by the user, but the ones here are standard.

c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()
x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tagPrefix:tagType attribute1="VALUE1" ...

or, as functions to create expressions:

tagPrefix:function(arg1,arg2,...)

As in XML, tags can be complete, using a single tag ending with “/>“, or in pairs, containing a content terminated by a matching ending tag </tagPrefix:tagType>. Some example of the common usages of the “c” tags are these:

<c:out value="EL-EXPRESSION" />
<c:set var="x" value="EL-EXPRESSION" />
<c:if test="EL-EXPRESSION" >  ...  </c:if>
<c:forEach var="x" items="EL-EXPRESSION" > ... </c:forEach>

The syntax for what replaces the “EL-EXPRESSION” in the above examples is specified by the Java-like EL language. EL is part JSP itself, although most common usages of it require additional the additional JSTL tags. EL expressions are all surrounded by the syntax ${ }.

EL is closely related to Java with some extensions and conceptual simplifications. In particular, EL follows the looser syntax common to other web scripting languages. EL expressions permit variables and most of the usual arithmetic and boolean operators.

Basic Syntax Features

  • The == operator for strings replaces like the Java .equals operator.
  • An EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string and is often printed as the empty string.
  • EL has a unary operator emptyempty(x) is true if x==null or x is the empty string.
  • The operators orand are synonyms for ||&&, respectively.

EL session variables

Any session variable x automatically becomes available as an EL variable, e.g. if we have:

<%   session.setAttribute( "x", "hello" );
     // or
     pageContext.setAttribute( "x", "hello" );   %>
...
x = ${x} <!-- prints: x = hello -- >

EL recognizes all the standard collection types. Elements from Arrays and Lists are both accessed by [ ] operator. Maps permit key access also via the [ ] operator. The EL expressions for maps, sets and lists can all print directly. Arrays, as in Java, don’t print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,",")}

This is an example:


session-elements.jsp
<%@ page language="java" contentType="text/html; 
    charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@page import="java.util.*"%>

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Session Elements</title>
</head>
<body>
<%
  String x = "testing";
  String[] a = { "xx", "yy", "zz" };

  Map<String, String> m = new LinkedHashMap<String, String>();
  m.put("aa", "1");
  m.put("bb", "2");
  m.put("cc", "3");

  List<String> l = new ArrayList<String>();
  l.add("nn");
  l.add("mm");
  l.add("oo");

  Set<String> s = new LinkedHashSet<String>();
  s.add("aa");
  s.add("bb");
  s.add("cc");

  session.setAttribute("x", x);
  session.setAttribute("a", a);
  session.setAttribute("m", m);
  session.setAttribute("l", l);
  session.setAttribute("s", s);
%>
<h2>print session elements</h2>
(String) x: ${x}<br />
(Array) a: ${fn:join(a,",")}<br />
(List) l: ${l}<br />
(Map) m: ${m}<br />
(Set) s: ${s}<br />

<h2>Array, List, Map access</h2>
a[1]: ${a[1]} <br />
l[2]: ${l[2]} <br />
m["bb"]: ${m["bb"]} <br />

</body>
</html>

Iterating over data structures

EL variables can also be created in a number of ways, typically as temporary variables needed to effect some operation such as iteration. In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!-- L represents either an array, list or set -->
<c:forEach var="x" items="${L}" > 
  ${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!-- M is a map -->
<c:forEach var="x" items="${M}" > 
  ${x.key}: ${x.value}
</c:forEach>

This is an example:


iteration.jsp
<%@ page language="java" contentType="text/html; 
         charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>iteration with c:forEach loop</title>
  </head>
  <body>
    <h2>iteration with c:forEach loop</h2>
    a: 
    <c:forEach var="i" items="${a}">
      ${i} 
    </c:forEach><br />
    s: 
    <c:forEach var="i" items="${s}">
      ${i} 
    </c:forEach><br />
    l: 
    <c:forEach var="i" items="${l}">
      ${i} 
    </c:forEach><br />
    m: 
    <c:forEach var="i" items="${m}">
      ${i.key} => ${i.value} &nbsp;
    </c:forEach><br />
  </body>
</html>

Other c: tags

An EL variable can be created and initialized directly with the c:set tag:

<c:set var="str" value="..." />

This can then be used in other later EL expressions. For example we may want to dump it into HTML code in one of two ways:

${str}                                          ${fn:escapeXml(str)}

The latter version, using the fn:escapeXml function literalizes the text for insertion into HTML. An equivalent alternative way to achieve the output uses the c:out tag in which the default behavior is to escape for HTML insertion.

<c:out value="${str}" escapeXml="false" />      <c:out value="${str}" />

The c:if tag generates a choice situation with a syntax like:

<c:if test="${EL_BOOLEAN_EXPRESSION}" > ... </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above.

If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
  <c:when test="${EL_EXPR1}"> ... </c:when>
  <c:when test="${EL_EXPR2}"> ... </c:when>
  ...
  <c:otherwise> ... </c:otherwise>
</c:choose>

This example illustrates the display features:


display-examples.jsp
<%@ page language="java" contentType="text/html; 
    charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@page import="java.util.*"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>

<h2>display examples with c:set, c:out, escapeXml</h2>
<c:set var="str" value="<b>bold</b>" />
str: ${str}<br />
escaped(str): ${fn:escapeXml(str)}<br />
c:out escaped: <c:out value="${str}" /><br />
c:out unescaped: <c:out value="${str}" escapeXml="false" />

</body>
</html>

JSP beans in JSTL

The EL language provides a simplified syntax for accessing bean’s get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id="mb" />

from the class:


bean/MyBean.java
package bean;
public class MyBean {
  private String count;
  public String getCount() { return count; }
  public void setCount(String count) { this.count = count; }
  public MyBean() { 
    System.out.println("MyBean intialized");
    count =  "0";
  }
}

EL treats the expression ${mb.count} as the value of mb.getCount() in a usage something like this:

<c:set var="i" value="${mb.count}" />

The c:set tag calls the set member function; e.g., mb.setCount("5") is this:

<c:set target="${mb}" property="count" value="5" />

Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { ... }
void setSomeProperty(int n) { ... }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target="${mb}" property="someProperty" value="5" />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var="mb" />

Here is an example:


bean-access.jsp
<%@ page language="java" contentType="text/html; 
    charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:useBean id="mb" scope="session" />

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>bean access example</title>
</head>
<body>

<h2>bean access example: bean.MyBean mb</h2>
<p>Refresh to observe changes</p>
<p>mb.count: ${mb.count}</p>
<c:set target="${mb}" property="count" value="${mb.count + 1}" />
<p>after incrementing, mb.count: ${mb.count}</p>
<c:choose>
  <c:when test="${mb.count > 6}">
    became bigger than 6, re-initialize mb
    <c:remove var="mb" />
  </c:when>
  <c:when test="${mb.count > 3}">
    became bigger than 3
  </c:when>
  <c:otherwise>
    no more than 3
  </c:otherwise>
</c:choose>

</body>
</html>

Query parameters

The value of parameter “xx” is expressed in EL by param.xx. This expression:

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter("xx") != null) ? request.getParameter("xx") : "" %>

Additionally, a multivalued parameter can be captured as an array by:

${paramValues.xx}

Here is an example:


query-params.jsp
<%@ page language="java" contentType="text/html; 
         charset=US-ASCII" pageEncoding="US-ASCII"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Values of query parameter p</title>
  </head>
  <body>
    <h2>Values of query parameter p</h2>
    <p>run this with
      <ul> <li>no query string</li>
           <li>query string <tt>?p=1</tt></li>
           <li>query string <tt>?p=1&amp;p=2</tt></li>
      </ul>
    </p>
    <c:if test="${param.p == null}"> param.p not defined<br /> </c:if>
    param.p first value: ${param.p}<br />
    param.p all values: ${fn:join(paramValues.p,",")}
  </body>
</html>


© Robert M. Kline
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s