You are on page 1of 33

Chapter 9

JSP Standard Tag Library (JSTL)

Introduction
y JSP actions and JSP EL is not enough powerful to implement y y

y y

complex presentation logic. They lack in basic features such as looping and storing scoped variables, and they have limited conditional logic. Custom tag has solved this issue till certain limit, but it would be terrible waste of time if every developer have to write his or her own if tags, for loop tags This is where JSTL comes in picture. JSTL provides many useful tag libraries and has been universally excepted by the Java community, so much so that it became its own specification.

Cont
y Although this specification is not part of the JSP specification, its

y y y y

very closely related and the Sun Certified Web Component Developer (SCWCD) certification requires the knowledge of its core tag library to pass the exam. The most commonly used JSTL tag library is the core library. Version 1.1 of this library is the focus of this chapter. It contains the following tags: out, if, forEach, forTokens, choose, when, otherwise, set, remove, import, url, param, redirect, and catch.

Installation of JSTL
y Because JSTL is a specification, more than one implementation of

this specification is possible. y Apache Foundations Jakarta Taglibs project provides a very popular implementation of JSTL and thats the one we use in this chapter. y To import JSTL into a Web application, follow these steps. 1. Download JSTL.
y

y y

You can download the implementation by following this URL: http://jakarta.apache.org/site/downloads/downloads_taglibsstandar d.cgi. The Web page offers you two options for download, either a .zip format or .tar.gz format. Usually, users of Windows download the .zip format file and users of UNIX-based systems download the .tar.gz format file.

Cont
2.
y

Unzip it to a directory.
The directory can be any directory on your hard drive. Because Apache implementation ships with some supporting material (e.g., a sample Web application), we dont need to copy all of it into our Web app.

3.
y y

Copy standard.jar and jstl.jar into the WEB-INF/lib of your application.


These JAR files are located in the directory to which you unzipped the downloaded file in the jakarta-taglibs-standard-1.1.2/lib directory. You need both of these JARs because jstl.jar contains only the interfaces that the JSTL specification requires these tags to implement and standard.jar contains the actual implementations along with the TLD files.

Cont
4.

Import the library into your JSP page with the taglib directive.
y It uses the same taglib directive mechanism as in the following. y Note the uri value shown. This is the URI that imports the core JSTL tag

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


y The prefix we assigned to the core JSTL tag library in Step 4 is "c". y This prefix can be anything you want. y However, its a known convention that the JSTL core tag library is

assigned "c" as the prefix and you should stick to that whenever possible. y Following universally accepted conventions makes the code easier to read.

c:out Tag
y The c:out tag is very similar to JSP scripting expressions like <%=

y y y y

... %> and standard JSP EL use like ${...}, but it has many advantages. Unlike the JSP scripting, its a regular tag, so it makes the HTML look cleaner. Unlike JSP EL, the c:out tag lets the JSP developer specify a default value to output if the resulting expression evaluates to null. It also has an attribute that allows the tag to automatically escape any XML type characters like <, >, &, ", '. c:out tag converts those special characters into the HTML equivalent characters. For example, the character < would be converted to &lt;.

Cont
y Because the old containers, pre-JSP 2.0, do not understand the

JSP EL, the c:out tag can also be used as a portable alternative to JSP EL, if support for older containers is important to your application. y In the next example we check c:out tag for following things
y To output special characters, < and >. y To output the bean which is not specified in any scope, so the

expression evaluates to null.

Example : c:out Tag


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <TITLE><c:out value="<c:out> Tag"/></TITLE></HEAD> <BODY> <H1 ALIGN="center"> <CODE> <c:out value="<c:out> Tag"/> </CODE> </H1> <UL> <LI>Subscription ID: <c:out value="${account}" default="none"/> </LI> </UL> </BODY> </HTML>

Cont

c:forEach and c:forTokens Tags


y The c:forEach tag provides basic iteration, accepting many y y

different collection types. It can also function as a counter-based for loop, specifying a begin, end, and a step index. It uses the var attribute to allow the JSP developer to specify a key with which to refer to the current element through the iteration. The c:forTokens tag functions much like c:forEach except it is designed to iterate over a string of tokens separated by delimiters. What is considered a delimiter is customized through its required delims attribute

Cont
y In the next example we perform the following operations, y A loop to print odd numbers. y A loop to print list values. y A loop to print string values with specified delimiter as separator

Example: c:forEach &c:forTokens


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <BODY> <c:out value="<c:foreach>, <c:forTokens> Tags"/> <TABLE> <TR><TD> <UL> <c:forEach var="i" begin="1" end="10" step="2"> <LI>i = ${i}</LI> </c:forEach> </UL> </TD> <TD> <% java.util.List list = new java.util.ArrayList(); list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); list.add("Five"); request.setAttribute("list", list); %> <UL> <c:forEach var="item" items="${list}"> <LI>${item}</LI> </c:forEach> </UL> </TD>

Cont
<TD> <UL> <c:forTokens var="item"

items="<Once)Upon,A(Time%There...> delims="<),(%> > <LI>${item}</LI> </c:forTokens> </UL> </TD> </TR> </TABLE> </BODY> </HTML>

Cont

c:if Tag
y The c:if tag is a simple conditional tag that evaluates its body if

the supplied condition is true. y The condition is evaluated through its required attribute test. y In the next example we use the c:if tag inside the loop to conditionally output the words greater than 3 if the current index of the loop is in fact greater than 3

Cont
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD><TITLE><c:out value="<c:if> Tags"/></TITLE></HEAD> <BODY> <H1 ALIGN="center"><CODE><c:out value="<c:if> Tag"/></CODE></H1> <UL> <c:forEach var="i" begin="1" end="10" step="2"> <LI> i = ${i} <c:if test="${i > 3}">(greater than 3)</c:if> </LI> </c:forEach> </UL> </BODY> </HTML>

Cont

c:choose Tag
y The c:choose tag is a conditional tag that establishes a context for

mutually exclusive conditional operations, marked by the c:when and c:otherwise tags. y These three tags work much in the same way as the standard Java switch-case-default statements. y The c:when tag functions in exactly the same way as the c:if tag. It has a test attribute that allows the JSP developer to specify a condition, which if evaluated to true, would signal to the container to evaluate the body of the c:when tag. If a particular c:when tags condition evaluates to true, no other c:when tags below it are evaluated and the processing jumps to the line after the closing c:choose tag. y If the optional c:otherwise tag is specified and no c:when tag evaluates to true, the body of the c:otherwise tag is evaluated

y In this example we iterate through numbers 1 through 10 and output different

messages depending on what the current iteration index is.

<BODY> <c:out value="<c:choose>, <c:when>, <c:otherwise> Tags"/></CODE></ <UL> <c:forEach var="i" begin="1" end="10"> <LI> i = ${i} <c:choose> <c:when test="${i < 3}">(less than 3)</c:when> <c:when test="${i < 5}">(less than 5)</c:when> <c:when test="${i == 5}">(It IS 5! SO exciting!)</c:when> <c:otherwise>(greater than 5)</c:otherwise> </c:choose> </LI> </c:forEach> </UL>

Cont

c:set and c:remove Tags


y The c:set tag is used for setting a scoped attribute or updating and creating

bean properties and map values. y The following are some of the common forms in which the c:set tag is used.
y <c:set var="attributeName" value="someValue" /> y <c:set

target="map" property="elementKey" value="elementValue" /> y <c:set target="bean" property="name">John Dow</c:set>


y The last c:set tag does not specify the value attribute. Its value comes from

the body of the c:set tag. y Its often the case that the value we want to set contains characters or dynamic expressions that are either difficult or sometimes simply impossible to place inside a tag attribute (i.e., value) in a legal way.

Cont
y The c:set tag provides two attributes, var and target, of which at least one

is required. These attributes are not allowed to appear at the same time. y The var attribute

y It is used to specify the name of an attribute to set. y This attribute is set in the scope specified by the optional scope attribute. y If the scope attribute is not specified, it defaults to page scope.

y The target attribute


y It must be an expression that evaluates to some object. y If the object implements the Map interface, the property attribute of the c:set

tag is treated as a key with which to create a new map entry with the value specified. y If the target evaluates to a JavaBean, the value of the c:set tag is passed to the property of the target JavaBean specified by the property attribute

Cont
y The c:remove tag.
y The c:remove tag allows the JSP author to specify the name of the

attribute to remove using the required var attribute and the scope to remove it from using the optional scope attribute. y Unlike the c:set tag, if the scope attribute is not specified, the c:remove tag will remove the attribute from all scopes.

<c:out value="<c:set>, <c:remove> Tags"/> <c:set var="map" value="<%= new java.util.HashMap() %>" scope="request"/> <c:set target="${map}" property="partialTitle" value="<read-it>Core</read-it>"/> <c:set target="${map}" property="fullTitle"> <c:out value="${map.partialTitle}"/> <BR> Servlets and JSP Volume 2 </c:set> <H1>${map.fullTitle}</H1> <c:set var="authors value="Marty Hall, Larry Brown,Yaakov Chaikin" scope="request"/> <c:set var="authors">Authors</c:set> <H2>${authors}: ${requestScope.authors}</H2> <c:remove var="authors"/> <H2>${pageScope.authors}: ${requestScope.authors}</H2>

Cont

c:import Tag
y The JSP framework provides a couple of ways to include content from the

same container.

y Static inclusion by using the include directive (page translation time) y Dynamic inclusion by using the jsp:include standard action (request time)

y Both of these types of inclusion mechanisms the included content has to

provide only a snippet of HTML. y However, what if the content we want to include resides on a different server?
the c:import JSTL tag can.

y The include directive as well as the jsp:include standard action cant help us there, but

y This tag can include the content, pointed to by the required attribute url,

even if the content resides on a different Web server. y The default behavior of c:import is to output the included content into the including page at the place where c:import appears.

Cont
y However, if the optional var and the likewise optional scope attributes are

specified, the included content can be saved as a scoped attribute instead. If the scope attribute is omitted, it defaults to the page scope. y Note :-The imported content has to be a snippet of HTML that fits into thestructure of your existing HTML page.The links inside the imported content have to be absolute.

c:url and c:param Tags


y C:url is used to create url with some optional parameters. y The c:url tag is able to hold off on outputting the URL string if the

optional var attribute is present. y In such a case, the resulting URL gets stored in a scoped attribute. y The scope can be specified by the optional scope attribute. y If omitted, the scope defaults to page scope, as usual. y Attributes in c:url tag var Declare a scoped variable that stores the url. scope Define the scope for declared variable like page or request or session or application. value Value attribute define a String that is used to specify a url that will process as url later.

Cont
y Example:<c:url

value="myurl?fullName=${fullNameParam}"/> y However, what if the fullNameParam turns out to be John Dow, with the space character in it? Spaces are illegal inside URLs, so we need to encode the parameters as well. y This is quite easily done with one or more c:param tags nested inside the c:url tag. y The c:param tag supplies the c:url tag with the name and value of request parameters for the URL with its required attributes called name and value.

Cont
<c:url value="/out.jsp" var="inputUrl"> <c:param name="name" value="John Dow"/> </c:url>

c:redirect Tag
y The c:redirect tag is used for redirecting URLs in JSP pages. y If its required url attribute specifies an absolute URL, y The c:redirect tag acts just like the sendRedirectURL method of the

HttpServletResponse class. y This results in the browser making an additional request to the new URL, and in fact is no different than if the user were to type the URL by hand. y If its required url attribute specifies an relative URL, y A dynamic forward occurs, which is equivalent to the forward method of the RequestDispatcher class. y In this case, the browser address bar still shows the original URL and not the URL of the forwarded to page. y The c:redirect tag can take advantage of the automatic encoding provided by nesting one or more c:param tags in its body.

c:catch Tag
y The c:catch tag acts like the try/catch construct in Java, except in the case

of c:catch, there is no try. y If you surround part of the page that may throw an exception with the c:catch tag, and an exception occurs, the page will still render up until the point where the exception occurred and then continue rendering from the c:catch end tag on. y You can store the thrown exception in a page scoped attribute specified by the optional var attribute. y Note :- Avoid using the c:catch tag for anything other than debugging or experimentation. Exception handling should be part of the business logic code, not the JSP page.

You might also like