JSTL- JSP Standard Tag Library Tutorial

Download Report

Transcript JSTL- JSP Standard Tag Library Tutorial

JSTL
JSP Standard Tag Library
8-Apr-16
WHAT IS JSTL?


JSTL (JSP Standard Tag Libraries) is a collection of JSP
custom tags developed by Java Community Process, www.jcp.org.
The reference implementation is developed by the Jakarta project,
jakarta.apache.org.
Full JSTL
– Contains many common and useful JSP custom tags
– Particularly useful when you are using MVC, but the data contains a
varying number of entries
– Based on the Struts looping and logic tags
– Not part of the JSP 1.2, 2.0, or 2.1 specs.
It is a separate specification that requires a separate download.


The JSP Standard Tag Library (JSTL) is a very new component
released by Sun for JSP programming.
JSTL allows you to program your JSP pages using tags, rather
than the scriptlet code that most JSP programmers are already
accustomed to. JSTL can do nearly everything that regular JSP
scriptlet code can do.
INSTALLING JSTL




To use JSTL, you must have a JSP 1.2 (or higher) container
installed. One of the most commonly used JSP containers is the
Apache Tomcat Web server. You can obtain a copy of Tomcat from
http://jakarta.apache.org/tomcat/. Using Tomcat alone will allow
you to use regular JSP scriptlet code. To use JSTL, you must
install JSTL into Tomcat. JSTL can be obtained from the same
source as Tomcat.
The main URL for JSTL is http://java.sun.com/products/jsp/jstl/.
You get jstl-api-1.2.jar and jstl-impl-1.2.jar from this site. To use
JSTL, you must unzip the distribution files and install them into
the correct locations within Tomcat.
For Older Versions, we will also need jstl.jar and standard.jar
which you can download from
http://archive.apache.org/dist/jakarta/taglibs/standard-1.0/
In fact choose the binaries :
http://archive.apache.org/dist/jakarta/taglibs/standard-1.0/binaries/
Note : For more details on versions and taglibs, refer to the preface
page at the end of this sesssion.
INSTALLING JSTL

1.
To properly install JSTL for use with Tomcat, follow these three
steps:
Copy the JSTL JAR files to Tomcat's lib directory.
If you are using Windows, the likely location of your lib directory
is C:\Apache Tomcat 6.0\webapps\ROOT\WEB-INF\lib. There
are a number of JAR files included with the JSTL release. You
should copy each of these JAR files to the Tomcat JAR directory.

2.
In Tomcat 6.0, copy it to C:\Apache Tomcat 6.0\lib and if you are using
older version say Tomcat5.5, copy it to C:\Apache Tomcat
5.5\common\lib
Copy the JSTL TLD files to Tomcat's web-inf directory.
The web-inf directory is likely at this location: C:\Apache Tomcat
6.0\webapps\ROOT\WEB-INF. If you examine the JSTL
distribution files, you should notice eight files that end with the
TLD extension. All eight files should be copied to your web-inf
directory.
INSTALLING JSTL
3.
Modify the web.xml file to include the TLD files.
Finally, you must modify your web.xml, and add an entry for all
eight of the tag libraries that you added. This consists of adding
<taglib> directives inside the main <web-app> directive. The entries
you should add are listed here.
<taglib>
<taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
<taglib-location>/WEB-INF/fmt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/fmt-rt</taglib-uri>
<taglib-location>/WEB-INF/fmt-rt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
INSTALLING JSTL
<taglib>
<taglib-uri>http://java.sun.com/jstl/core-rt</taglib-uri>
<taglib-location>/WEB-INF/c-rt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/sql</taglib-uri>
<taglib-location>/WEB-INF/sql.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/sql-rt</taglib-uri>
<taglib-location>/WEB-INF/sql-rt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/x</taglib-uri>
<taglib-location>/WEB-INF/x.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/x-rt</taglib-uri>
<taglib-location>/WEB-INF/x-rt.tld</taglib-location>
</taglib>
INSTALLING JSTL


After completing the preceding three steps, you are now
ready to test your installation of JSTL. This can be done
by creating a JSP page that uses JSTL. A very simple
example would be the "count to ten" example. You
should place your JSP file inside the Webroot directory
(C:\Apache Tomcat 6.0\webapps\ ROOT). Once the
Tomcat server is started, you should be able to browse to
http://localhost:8080/count.jsp to see your page.
If you do not have JSTL installed correctly, there will
likely be no error message. If JSTL is not interpreting
your tags, they will be passed through directly to the
Web browser. The Web browser will interpret these tags
as unknown HTML tags. Most browsers simply ignore
the unknown HTML tags.
COUNT TO TEN



EXAMPLE USING SCRIPTLET:
JSTL was introduced to allow JSP programmers to program using tags rather
than Java code.
To show why this is preferable, a quick example is in order. We will examine a
very simple JSP page that counts to ten.
We will examine this page both as regular scriptlet-based JSP, and then as JSTL.
When the count to ten example is programmed using scriptlet based JSP, the JSP
page appears as follows.`
<html>
<head>
<title>Count to 10 in JSP scriptlet</title>
</head>
<body>
<%
for(int i=1;i<=10;i++)
{%>
<%=i%><br/>
<%
}
%>
</body>
</html>



As you can see from the preceding example, using scriptlet code
produces page source code that contains a mix of HTML tags and
Java statements. There are several reasons why this mixing of
programming styles is not optimal.
The primary reason that it is not optimal to mix scriptlet and tagbased code is readability. This readability applies both to humans
and computers. JSTL allows the human programmer to look at a
program that consists entirely of HTML and HTML-like tags.
The readability of JSP scriptlet code does not just apply to human
beings. The mixing of scriptlet and HTML code is also hard for
computers to read. This is particularly true of HTML authoring
tools such as Someone's Dreamweaver and Microsoft FrontPage.
Currently, most HTML authoring tools will segregate JSP
scriptlet code as non-editable blocks. The HTML authoring tools
usually do not modify the JSP scriptlet code directly.
COUNT TO TEN
EXAMPLE USING JSTL:
The following code shows how the count to ten example would be written
using JSTL. As you can see, this code listing is much more constant, as only
tags are used. HTML and JSTL tags are mixed to produce the example.
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Count to 10 Example (using JSTL)</title>
</head>
<body>
<c:forEach var="i" begin="1" end="10" step="1">
<c:out value="${i}" />
<br />
</c:forEach>
</body>
</html>



When you examine the preceding source code,
you can see that the JSP page consists entirely of
tags.
The above code makes use of HTML tags such as
<head> and <br>. The use of tags is not confined
just to HTML tags. We can modify that code to
print numbers from 1 to n. The code is given in
the next slide.
This code also makes use of JSTL tags such as
<c:forEach> and <c:out>. In this article you will
be introduced to some of the basics of JSTL.
PRINT 1 TO N EXAMPLE USING JSTL:
The following code shows how the count to n example would be written using
JSTL. As you can see, this code listing is much more constant, as only tags
are used. HTML and JSTL tags are mixed to produce the example. You can
just use http://localhost:8080/count1.jsp?number=10 to see the result.
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<c:set var="n" value="${param.number}" />
Hello ...Printing numbers till N=
<c:out value="${n}"/>
<br/>
<br/>
<c:forEach var="i" begin="1" end="${n}" step="1">
<c:out value="${i}"/>
</c:forEach>
</BODY>
THE JSTL TAG LIBRARIES
The JavaServer Pages Standard Tag Library
(JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many
JSP applications. JSTL is often spoken of as a
single-tag library.
 JSTL has support for common, structural tasks
such as iteration and conditionals, tags for
manipulating XML documents,
internationalization tags, and SQL tags. It also
provides a framework for integrating existing
custom tags with JSTL tags.
 The JSTL tags can be classified, according to
their functions, into following JSTL tag library
groups that can be used when creating a JSP
page:

THE JSTL TAG LIBRARIES
The JSTL tags can be classified, according to their functions,
into following JSTL tag library groups that can be used when
creating a JSP page:





Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
THE JSTL TAG LIBRARIES





Core Tag Library—Contains tags that are essential to nearly any Web
application. Examples of core tag libraries include looping, expression
evaluation, and basic input and output.
Formatting/Internationalization Tag Library—Contains tags that
are used to parse data. Some of these tags will parse data, such as dates,
differently based on the current locale.
Database Tag Library—Contains tags that can be used to access SQL
databases. These tags are normally used only to create prototype
programs. This is because most programs will not handle database access
directly from JSP pages. Database access should be embedded in EJBs
that are accessed by the JSP pages.
XML Tag Library—Contains tags that can be used to access XML
elements. Because XML is used in many Web applications, XML
processing is an important feature of JSTL.
JSTL Functions --JSTL includes a number of standard functions, most
of which are common string manipulation functions.
CORE TAGS:
The core group of tags are the most frequently used JSTL tags. Following is
the syntax to include JSTL Core library in your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Tag
Description
<c:out >
Like <%= ... >, but for expressions.
<c:set >
Sets the result of an expression evaluation in a 'scope'
<c:remove >
Removes a scoped variable (from a particular scope, if specified).
<c:catch>
Catches any Throwable that occurs in its body and optionally exposes it.
<c:if>
Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>
<c:when>
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise >
Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'.
<c:import>
Retrieves an absolute or relative URL and exposes its contents to either the page,
a String in 'var', or a Reader in 'varReader'.
<c:forEach >
The basic iteration tag, accepting many different collection types and supporting
subsetting and other functionality .
<c:forTokens>
Iterates over tokens, separated by the supplied delimeters.
<c:param>
Adds a parameter to a containing 'import' tag's URL.
<c:redirect >
Redirects to a new URL.
<c:url>
Creates a URL with optional query parameters
FORMATTING TAGS:
The JSTL formatting tags are used to format and display text, the date, the
time, and numbers for internationalized Web sites. Following is the syntax to
include Formatting library in your JSP:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of Formatting JSTL Tags:
Tag
Description
<fmt:formatNumber>
To render numerical value with specific precision or format.
<fmt:parseNumber>
Parses the string representation of a number, currency, or
percentage.
<fmt:formatDate>
Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate>
Parses the string representation of a date and/or time
<fmt:bundle>
Loads a resource bundle to be used by its tag body.
<fmt:setLocale>
Stores the given locale in the locale configuration variable.
<fmt:setBundle>
Loads a resource bundle and stores it in the named scoped variable or
the bundle configuration variable.
<fmt:timeZone>
Specifies the time zone for any time formatting or parsing actions
nested in its body.
<fmt:setTimeZone>
Stores the given time zone in the time zone configuration variable
<fmt:message>
To display an internationalized message.
<fmt:requestEncoding>
Sets the request character encoding
SQL TAGS:


The JSTL SQL tag library provides tags for interacting with relational
databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Tag
Description
<sql:setDataSource> Creates a simple DataSource suitable only for
prototyping
<sql:query>
Executes the SQL query defined in its body or
through the sql attribute.
<sql:update>
Executes the SQL update defined in its body or
through the sql attribute.
<sql:param>
Sets a parameter in an SQL statement to the
specified value.
<sql:dateParam>
Sets a parameter in an SQL statement to the
specified java.util.Date value.
<sql:transaction >
Provides nested database action elements with a
shared Connection, set up to execute all
statements as one transaction.
XML TAGS:

The JSTL XML tags provide a JSP-centric way of creating and
manipulating XML documents. Following is the syntax to include
JSTL XML library in your JSP:
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

The JSTL XML tag library has custom tags for interacting with
XML data. This includes parsing XML, transforming XML data,
and flow control based on XPath expressions.
Before you proceed with the examples, you would need to copy
following two XML and XPath related libraries into your <Tomcat
Installation Directory>\lib:
XercesImpl.jar: Download it from http://www.apache.org/dist/xerces/j/
 xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html

Following is the list of XML JSTL Tags:
Tag
Description
<x:out>
Like <%= ... >, but for XPath expressions.
<x:parse>
Use to parse XML data specified either via an
attribute or in the tag body.
<x:set >
Sets a variable to the value of an XPath expression.
<x:if >
Evaluates a test XPath expression and if it is true, it
processes its body. If the test condition is false, the
body is ignored.
<x:forEach>
To loop over nodes in an XML document.
<x:choose>
Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise>
<x:when >
Subtag of <choose> that includes its body if its
expression evalutes to 'true'
<x:otherwise >
Subtag of <choose> that follows <when> tags and runs
only if all of the prior conditions evaluated to 'false'
<x:transform >
Applies an XSL transformation on a XML document
<x:param >
Use along with the transform tag to set a parameter in
the XSLT stylesheet
JSTL FUNCTIONS:
JSTL includes a number of standard functions, most of which are common
string manipulation functions. Following is the syntax to include JSTL
Functions library in your JSP:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Following is the list of JSTL Functions:
Function
fn:contains()
Description
Tests if an input string contains the specified substring.
fn:containsIgnoreCase( Tests if an input string contains the specified substring
)
in a case insensitive way.
fn:endsWith()
Tests if an input string ends with the specified suffix.
fn:escapeXml()
Escapes characters that could be interpreted as XML
markup.
fn:indexOf()
Returns the index within a string of the first occurrence
of a specified substring.
fn:join()
Joins all elements of an array into a string.
fn:length()
Returns the number of items in a collection, or the
number of characters in a string.
fn:replace()
Returns a string resulting from replacing in an input
string all occurrences with a given string.
fn:split()
Splits a string into an array of substrings.

In this session, we will only take a brief look at a
few of the core tags. We will examine a simple
example that shows how to process data that a
user enters into a form. Before we examine this
program, we must first see how JSTL handles
expressions. Expression handling in JSTL is
accomplished by using the EL expression
language, just as it is done in JSP 2.0. In the
subsequent sessions, we will examine the EL
expression language.
THE EL EXPRESSION LANGUAGE

One major component of JSP 2.0 is the new expression language named EL. EL is used
extensively in JSTL. However, it is important to remember that EL is a feature of JSP and
not of JSTL. JSP scriptlet code used with JSP 2.0 can contain EL expressions. The following
lines of code demonstrate using EL inside of JSP scriptlet code:
<p>
Your total, including shipping is ${total+shipping}
</p>

As you can see from the preceding code, the values "total" and "shipping" are added and
displayed as the HTML is generated. These expressions can be used inside of JSTL tags as
well. One important requirement of JSTL 1.0 was that JSTL could be used with JSP 1.2.
Because JSP 1.2 does not support EL, it is necessary to provide a few additional JSTL tags
that facilitate the use of EL. For example, if you wanted to use JSTL to display the above
expression, you would use the following code.
<p>
Your total, including shipping is <c:out var="${total+shipping"/>
</p>

One of the requirements of JSTL was that it not require JSP 2.0 to run. By providing a tag
that is capable of displaying EL expressions, this requirement is met.
JSTL EXAMPLE
We will now examine a simple example that uses JSTL. For this example, we
will examine a common procedure that is done by many Web applications.
We will see how to POST a form and process the results from that POST. A
simple program that is capable of doing this is shown below:
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>If with Body</title>
</head>
<body>
<c:if test="${pageContext.request.method=='POST'}">
<c:if test="${param.guess=='Java'}">You guessed it!
<br />
<br />
<br />
</c:if>
JSTL EXAMPLE…CONTD
<c:if test="${param.guess!='Java'}">You are wrong
<br />
<br />
<br />
</c:if>
</c:if>
<form method="post">Guess what computer language
I am thinking of?
<input type="text" name="guess" />
<input type="submit" value="Try!" />
<br />
</form>
</body>
</html>
This simple Web page will display a form and ask the user to guess what computer
language the program is thinking of. Of course, the computer is thinking of "Java." This
page begins by checking to see if a POST was done. This allows both the form, and the
code that handles the form, to be placed on one single page. This is done with the
following JSTL if statement.
<c:if test="${pageContext.request.method=='POST'}">
Here you can see that the <c:if> tag uses an EL expression to evaluate whether the
request method is POST. If data was posted to the page, the value that the user
entered for their guess is stored in a parameter named "guess". This is because
"guess" was specified as the name of the form input item. We must now check to see
whether this parameter is equal to the word "Java". This is done with the following
<c:if> tag.
<c:if test="${param.guess=='Java'}">
You guessed it!
</c:if>
As you can see, the body of the <c:if> tag is executed if the statement evaluates
to true. In this article, we began to examine the basics of how JSTL is installed
and how it works. There is much more to JSTL than this small example.
The core tags of JSTL also include tags for looping, iteration, and variable
handling. By using these tags, you can iterate through collections, access user
session data, and perform other core tasks that all Web applications perform.
You can get more examples from the site.
Conclusion
•This tutorial showed you some of the differences between the JSTL and
standard JSP scriptlet programming. As you can see, JSTL allows a more
consistent programming environment by allowing both HTML and
procedural code to be expressed as tags. JSTL and tag libraries represent
a new method of programming Web pages.
•JSTL does not provide everything that a programmer would need to
create a full-featured Web application. Further, some procedures that could
be programmed in JSTL is often best not programmed in JSTL. One
perfect example of this is the database JSTL tags. Except for very small
Web applications, it is generally considered bad programming practice to
embed actual database commands into a JSP page. The proper location
for such program code is in Java beans and EJBs that will be used by your
Web application. For such routines, you may consider creating your own
tag libraries.
•This way, your JSP pages can use JSTL to perform basic programming
procedures that are not unique to your business. You should implement
your own tag libraries to implement components, which are unique to your
business, which will be used by your Web application.
JSTL allows you to create a very consistent programming JSP-based
application. This is done not just through JSTL, but through a combination
of JSTL, your own custom tag libraries, and an underlying database.
Understanding each of these components allows you to deploy an effective
Web application
PREFACE
JSTL TAGLIB DEFINITIONS

JSTL 1.2 (J2EE 5/JSP 2.1)
Download: http://jstl.java.net/download.html
 JSTL 1.2 consists of two files (jstl-impl-1.2.jar and jstl-api-1.2.jar) and is
available for download at the above link. It should be used for JSP 2.1
containers such as Tomcat 6.


Older Versions
Be aware that there are two jar files to the JSTL; generally named jstl.jar
and standard.jar. You need both.
 Be sure to use the appropriate version of the JSTL for your servlet container.
JSTL 1.1 should used for JSP 2.0 containers such as Tomcat 5 and Resin 3,
while JSTL 1.0 should be used for containers supporting JSP 1.n.


JSTL 1.1 (J2EE 1.4/JSP 2.0)






Download: http://archive.apache.org/dist/jakarta/taglibs/standard/
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
JSTL TAGLIB DEFINITIONS

JSTL 1.0 (J2EE 1.3/JSP 1.2)






Download: http://archive.apache.org/dist/jakarta/taglibs/standard-1.0/
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
Notes on Dynamic Attributes for JSTL Tags
Under JSTL1.1 and JSP2.0 you can use either scriplet expressions such as
<%= expr %> or EL expressions like ${expr} for JSTL tag attributes that
accept run-time expressions. Most attributes in JSTL tags are enabled for
run-time expressions, the most prevalent exceptions being the var and
scope attributes of tags that accept them.
 This is because under JSP 2.0 the responsibility for evaluating the
expressions lies with the container.
 Under JSTL1.0 and JSP 1.2, the JSTL is responsible for EL expression
evaulation and you need to choose whether you want to use ${expr} or <%=
expr %> notations. This is why two version of each tag set are provided; for
example the c library for EL expressions, and the c-rt library for use with
scriptlet expressions.
