ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button JSP and Servlets

JSP Standard Tag Libraries, Part 2

05/08/2002

This article is the second in a series on JSTL, the JSP Standard Tag Library. If you need a primer as to what JSTL encompasses, check out part one of this series.

In this article, we will cover more of the details of how to use the various tags in the different Tag Library Descriptors (TLDs). We'll go though samples using the conditionals, iteration, and URL, U18N, SQL, and XML tags. The goal of this article is to show the key components of the JSTL, learn how to use the tags, and discover how using the JSTL can improve your JSP development.

Let's quickly review what the JSTL is: a set of standard custom actions that can be used in various functional areas. JSR-52 of the Java Community Process, JSTL provides expression language support, control flow actions, and Tag Library Validators. The latest version of the specification, which is the proposed final draft, can be found on the jcp.org site.

JSTL requires you to run a JSP 1.2 container. The overriding theme of the JSTL is to simplify the development of JSPs and provide easy access and manipulation of application data. Using JSTL should make the page author's life easier.

JSTL consists of multiple Tag Library Descriptors included in one JAR file. These TLDs cover a range of functional areas, and we'll go through each one. But first, let's talk in more detail about the expression language support that is a prominent feature of the JSTL.

The expression language (EL) support is actually owned by the JSR-152 experts group, which, for those of you keeping track, is JSP 1.3. However, the expert groups for both JSR-52 and JST-152 have been working closely together. In fact, it looks like EL will actually become part of the JSP 1.3 specification. The EL (currently SPEL) provides an easy syntax for accessing application data directly. This allows for operators and bean and collection support, as well as automatic type conversion and the definition of default values for attributes.

Using Expressions

Expressions are invoked through the construct ${expression}. Expressions can be used only in attributes. For example:

<c:if test="${product.price >= customer.limit}">
...
</c:if>

In the above example, we are just using an expression to do a comparison, but it's also possible to mix an expression with static text. That might look something like:


<c:forEach var="current">
	<c:out value="Product-${current}"/>
</c:forEach>

In this sample, we are iterating over a collection and using the current item to append to the string product. That might result in an output that looks like:


Product-1
Product-2
Product-3...

As you can see from this example, the manipulation that has to be done when using JSTL is much cleaner than code written previously. Before JSTL, you needed to declare an Object, know the type of that Object, and understand some scripting language to even do a simple manipulation. Having to do all those steps led to some awkward syntax.

Now, with the JSTL, we have direct access to data using a much simpler syntax. The EL support is much better suited for taking care of these types of tasks.

As a simple sample, we can go from:


<jsp:useBean id="customer" type="sample.Customer" scope="request"/> ...
Customer Name: <%=customer.getName()%>
...
<% if (customer.getState().equals("CO")){ %>
...
<%}%>

to:


Customer Name: ${ customer. name}
<c:if test="${customer. state == param. state}">
...
</c:if>

The EL also allows for direct access to data in all supported JSP scopes. For example, we can access foo using ${foo} instead of pageContext.findAttributes("foo"). It's also possible to access beans and their properties using dot or indexed referencing. For example:


${user.address.city} 
${products.[product.id]}
${products.["Part-010"]}

Related Reading

Java Servlet Programming
By Jason Hunter

The expression language has all of the relational operators you would assume: ==, !=, <,>, <=, and >=, &&, ||, ! . Additionally, there are lt, gt, le, ge, eq, and ne operators, to avoid having to use the entity references in XML syntax. There are also the arithmetic operators: +,-,/,*,%, as well as Boolean operators and, or, not, and empty. Another feature of the expression language is that it provides automatic type coercion. For example, int value = "${request.myValue}" would be converted correctly.

It is possible to provide default values. These default values are also type correct. Default values are a useful way to avoid null-pointer exceptions on your page. The following sample shows how to set a var with a default value: <c:set var="city" value="${user.address.city}" default="N/A" />

Now that we've taken a look at some of the features of using an expression language, let's look at the EL supported actions.

Core Actions

The EL is used in the Core tag library. The <c:out> tag outputs EL expression evaluation to the current JspWriter. This is similar in functionality to JSP's <%= scripting exp %>. Using the core actions looks like:


<c:out value="${customer.name}"  default="N/A" />

It's also possible to set and remove scoped variables. The default scope used is Page. For example, we can set a Page scope variable called customer by using <c:set var="customer" value=${customer}" /> and then use <c:remove var="customer" /> to remove it from scope.

With the JSTL we can now use a tag to catch java.lang.Throwable, for example, <c:catch var="myError" />. Using this tag allows for uniform error handling to be declared on a page. This tag isn't meant to replace the existing JSP error page mechanism. By using the <c:catch> tag it becomes possible to have fine-grained error handling; this allows for errors to be handled by the page instead of going to the error page -- not every error that gets thrown really needs to go to the error page. By using the <c:catch> tag, it's possible to design better user interactions because the flow of the page is more user-friendly.

Conditional Actions

Using the expression language in conditional actions can also be a powerful mechanism to simplify JSP code. By using the <c:if> tag, it is possible to construct simple conditional expressions. For example, by accessing an Objects property like so:


<c:if test="${user.visitCount == 1}"
	Welcome back! 

</c:if>

you can see that when there is an if, surely there is an else. Mutually exclusive conditionals are useful when only one of a number of possible alternative actions are evaluated. It is possible to perform "if/then/else" functionality by using the <c:choose>, <c:when>, and <c:otherwise> tags.

Let's look at a sample. If we were processing through some result set, we could use these tags to determine what the correct message to display should be.


<c:choose>
<c:when test="${count == 0}">
	No records matched your selection.
</c:when>
<c:otherwise>
	<c:out value="${count}"/> records matched your selection.
</c:otherwise>
</c:choose>

Pages: 1, 2, 3

Next Pagearrow