Professional Documents
Culture Documents
In the first part of this tutorial on JSTL, the author gives a brief introduction to
JSTL and shows why and how it evolved.
As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP
page should encapsulate the business logic in a bean and invoke it by using
<jsp:useBean> tag. Till recently, a combination of Servlets, JSP and beans was the
standard practice. But, the JCP realeased an API for enabling programmers to create
custom tags and use them in their JSP pages. The difference between javabean and java
custom tags was that, though both made use of java classes, tags can be used by non-
programmers also without knowledge of Java programming, just as they would use html
tags.( From a programmer's perspective,however, a much more important distinction is
that tags are specific to the page in which they are created while javabeans are general. )
ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no
longer popular in Indian environment, though it is said to be very much in vogue still, in
US!
To correct this problem, Sun and JCP, initiated the JSP-Standard Tag Library
(JSTL) project. Though there are a number of popular and powerful tag-libraries, it is
always better for j2ee coders to adopt the JCP standard because, it is likely to be merged
into the core specification of Java langauage itself , in future. (That yardstick may be
valid for all creations, in Java world. Splintering of the Java platform due to' hyper-active
creativity' without the corresponding discipline to get it through a standards body ,is the
greatest threat, looming large in the Java-horizon.
Too frequent revisions and additions, that too without caring for backward
compatibility,are not conducive to programmer productivity and the net result is that
programmers spend ,in learning new twists in grammar, their precious time which
should have been spent more usefully in applying that grammar in solving business-logic
problems and acquiring proficiency in the chosen application-domain. While, tag library
is sometimes very elegant and simple to use, it defeats the very purpose if the tags are
not standard tags and if there is proliferation of non-standard tags.It is for this reason that
JSTL merits our serious study and adoption.
JSTL is a quite recent development. It was only in 2003, that the official version 1.1 was
released and now incorporated into JSP-2.
According to the latest position, the JCP is suggesting that a JSP page should be
completely free from any trace of Java code! So, programmers who were writing their
JSP using Javabeans and scriptlets , may not be able to carry on in their old style as, to
prevent programmers from introducing scripting sections in their pages, there is a
provision for turning off scriptlets altogether from a jsp page. If that happens ,all our
knowledge of Java coding will be of little use in creating a jsp page, though such
knowledge may be useful in creating beans and other types of java programs.
It is thus very important for J2EE students, to understand the trend and get to know the
techniques, advantages and limitations of tag libraries...In a way, a study of JSTL is
almost synonymous with a study of the latest version of JSP (ie) JSP2.0 .
---------------------------------------
Without an introductory demo for each of these types, it may be difficult to appreciate
the significance of the above lines. So we will now give simplest illustration.
==============================================
Servlets are full-fledged java-classes and so are very powerful. But, when we want to
create a dynamicalay-generated web-page using servlets, it becomes difficult and
clumsy.Let us consider a very simple example.
The user fills up text in html form with his name and submits the form,to the servlet. The
servlet reads the data , appends a greeting and sends it back to the user.
-----------------------------------------------
=============
<html> <body>
<form method=post
action= 'http://localhost:8080/servlet/greeting'>
<input type=text name='text1'>
<input type=submit>
</form>
</body>
</html>
-----------------------------------------------------------------------------
(relevant section of greeting.java servlet)
// greeting.java ( code-snippet only)
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//-------------------------------
String s = req.getParameter("text1");
out.println("<html><body bgcolor=yellow>");
out.println("we welcome"+",<br>");
out.println (s);
out.println("</body> </html>");
}
-----------------------------------------------
It will be noticed that we have to write so many 'out.println' statements. This makes the
page unreadable.( If String-buffer is used , we can do it with just a single out.println , but
forming the correct string may pose difficulties).
It is to solve this problem that JSP was developed five years back(1999).While a
servlet interposes HTML in java code, JSP interposes java-code in HTML, as some
authors correctly observe..( in this case, we have to modify the action field in html form,
so that it refers to the following greeting1.jsp).Student readers will know about
'delimiters' ( <%).in ASP.
This is the same as in JSP. Only the syntax is slightly different.In JSP parlance, the code
within delimiters is known as 'scriptlet'.( see greeting1.jsp)
-----------------------------------------------
// greeting1.jsp
<html>
<body bgcolor=yellow>
<%
String s = request.getParameter("text1");
out.println("we welcome"+<br>);
out.println(s);
%>
</body>
</html>
-----------------------------------------------
----------------------------------------------- // greeting2.jsp
<html>
<body bgcolor=yellow>
we welcome <br>
<%= request.getParameter("text1") %>
</body>
</html>
-----------------------------------------------
------------------------------------------
// greeter.java
//==============
package ourbeans;
public greeter() { }
public String greetme(String s) {
return "we welcome..."+s;
}
}
-------------------------------------------
'e:\tomcat5\webapps\root\WEB-INF\classes\ourbeans'
( Anytime, a new class is placed in Tomcat, we should remember to restart the server).
We can now write our JSP code as follows:
------------------------------------------------
// greeting3.jsp
<html>
<body>
<jsp:useBean id='bean1' class='ourbeans.greeter'>
<%
String s = request.getParameter ("text1");
String r = bean1.greeteme(s);
out.println(r);
%>
</body>
</html>
----------------------------------------------
We are now entering JSTL zone.
How exactly we should proceed to instal JSTL, we will take up shortly. For the
moment, we are just getting familiar with the required syntax. We begin with taglib
directive.
The directive says that we are using 'core' tags and the prefix will be 'c'. If we want to
assign the value 'sam' to a variable 'a' and then print it, the JSTL code will be
-----------------------------------
The Dollar sign & brace will be familiar ground for Perl programmers. In JSTL & JSP-
2, it is known as EL ( Expression Language).
==============================================
String s = request.getParameter("text1");
==================================
-----------------------------------------------
===========
-----------------------------------------------
In the previous examples, there was java code in a few lines atleast. But, in the JSTL
example, we find that there are only tags and no java scriptlets. This is the avowed
objective of the JSTL initiative,
under the auspices of Java Community Project! Why? This enables , clean separation of
Page author's role and Logic programmers' role. Thus maintenance becomes easy.
===============================================
There are five groups under which the JSTL tags have been organized.
2) xml
3) sql
4) formatting
5) functions.
It is good to start with this because, it contains a lot of valuable software , including the
latest and greatest from JCP, (ie) JSF
For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we
find four sub folders :
a) docs
b) lib
c) samples
a) standard.jar
b) jstl.jar
'e:\tomcat5\webapps\root\WEB-INF\lib'
-----------------------------------------------
( Remember to restart the Tomcat server). That is all that is required to use JSTL. !
***********************************************
( the results are not ensured for other environments.).( however, we adopted the
same method in Tomcat4.1 with jdk1.41 and got correct functioning.)
===============================================
The JSTL folder contains a sub-folder named 'tld'. There will be a number of tld files
there such as
c.tld, ( core)
x.tld, (xml)
fmt.tld, (format)
fn.tld. (functions)
------------------------------
..:\tomcat5\webapps\root\WEB-INF folder.
A few others , say that there is automatic detection and so it is not necessary. We chose
not to copy the tld files into
e:\tomcat5\webapps\root\WEB-INF folder !
( Schema serves the same purpose but is in XML format and is more powerful). ( The
default is DTD ).
This point is very important. The default allows us to use EL,(Expression Language) but
by using <c:out value="${s}" syntax.
If we modify the DTD into the prescribed J2EE schema , we can directly print as ${s}.
This requires very careful handling and we take it up later.
For the present , let us not tamper with the DTD. or the web.xml file.
In the second part of this tutorial on JSTL, the author explains how the tags in the
core-group can be used in JSP pages, with a number of simple examples.
‘http://java.sun.com/jstl/core'
'http://java.sun.com/jstl/core'.)
<c:set
<c:out
<c:if test= “
<c:choose , <c:when , <c:otherwise
<c:forEach
<c:forTokens
<c:import
<c:url
<c:redirect
<c:param
-----------------------------------------------
---------------------------------------
e:\tomcat5\webapps\root\demo1.jsp
-----------------------------------------
// demo1.jsp
----------- ---
The syntax is
<jsp:useBean
id="bean1" class="ourbeans.player" >
<jsp:setProperty
name="bean1" property="*" />
</jsp:useBean>
-----
But, we should first create the 'player ' bean with all
the attributes and getter & setter methods, as shown.
---------------------------------------------
// player.java
package ourbeans;
public class player{
String name;
String place;
String game;
public player(){
name=" ";
place=" ";
game=" ";
}
//---------------------------
---------------------------------
---
=============================================
// demo2.jsp
<html>
<body>
<form method=post action="demo2.jsp">
<jsp:useBean id="bean1" class="ourbeans.player">
<jsp:setProperty name="bean1" property="*" />
</jsp:useBean>
Name <input type=text name="name"><br>
Place<input type=text name="place"><br>
Game<input type=text name="game"><br>
<input type=submit>
</form>
=============================================
***********************************************
We are now ready to take up examples for 'condition' tags.
----------------------------------------------
//demo3.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<html>
<body bgcolor=lightblue>
<form method=post action=demo3.jsp>
<select name="combo1">
<option value="sam">sam
<option value="tom">tom
</select>
<input type=submit>
</form>
<c:set var="s" value="${param.combo1}" />
<c:out value="${s}" />
<br>
-----------------------------------------
'sam' and 'tom'. If the user selects 'sam' and submits the
form, he gets 'GoodMorning ...SAM!". If he selects 'tom'
instead, he gets
***********************************************
<c:choose >
<c:when test=" " >
<c:otherwise> something </c:otherwise>
</c:choose>
-----------------------------------------------
// demo4.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<html>
<body bgcolor=lightblue>
<form method=post action="demo3.jsp">
<select name="combo1">
<option value="1">1 </option>
<option value="2">2 </option>
<option value="3">3 </option>
<option value="4">4 </option>
<option value="5">5 </option>
<option value="7">7 </option>
</select>
<input type=submit>
<c:set var="s" value="${param.combo1}" />
Today is
<br>
<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>
<c:otherwise>
select between 1 & 5
</c:otherwise>
</c:choose>
</body>
</html>
---------------------------------------------
------------------------------------
//demo5.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<% pageContext.setAttribute("colors",
new String[]
{"red","green","blue","orange","black"} ); %>
<table>
<c:forEach var="n" items="${colors}"
varStatus="a">
<tr>
<td> <c:out value="${a.index}" /> </td> <td> <c:out
value="${a.count}" /> </td>
<td> <c:out value="${a.first}" /> </td>
<td> <c:out value="${a.last}" /> </td>
<td> <c:out value="${a.current}" /> </td>
<tr>
</c:forEach>
</table>
===============================================
Demo6 also deals with iteration tag.In the following example, the iteration starts at
value 3 and ends at value 8 .It displays the values of n in each iteration.Each iteration
increments the value of n automatically by 1,if step is not specified.
-----------------------------------------------
demo6.jsp
345678
===============================================
Demo7 deals with JSTL's 'forTokens' tag.<c:forTokens>, which iterates over a string of
tokens separated by a set of delimiters like the stringTokenizer class in Java.
--------------------------------------------
demo7.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<c:set var="s" value="SAM,DELHI,MCA,24,90" />
<html>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Place</th>
<th>Degree</th>
<th>Age</th>
<th>Mark</th>
</tr>
<tr>
<c:forTokens items="${s}"
delims="," var="token" >
<td><c:out value="${token}" /></td>
</c:forTokens>
</tr>
</table>
<br>
</font>
</body>
</html>
------------------------------------------
------------------------------------------
Attribute Description
===============================================
--------------------------------------------
// welcome.htm
<html>
<body>
WELCOME
<br>
</body>
</html>
---------
demo8.jsp
<%@ taglib prefix="c"
uri="http://java.sun.com/jstl/core" %>
<c:import url="welcome.htm"/>
<c:out value="to our web-site!" />
===============================================
--------------------------------------
demo9.jsp
--------------------------------------
===============================================
demo10.jsp
===============================================
----------------------------------------------
demo11.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<c:redirect url="http://localhost:8080/jstldemos/
core/sample.jsp" >
<c:param name="name1" value="SAM"/>
</c:redirect>
-------------------------------------------
( in a different file)
sample.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"
%>
<c:out value="${param.name1}"/>
demo12.jsp
----------------------------------------------
Similarly,
books.xml
-----------------------------------------------
demo1
The syntax:
<x:forEach var="n"
select="$doc/books/book">
-----
demo1.jsp
<html>
<body>
<c:import url="books.xml" var="url" />
<x:parse xml="${url}" var="doc" />
-----------------------------------------------<br>
<x:forEach var="n"
select="$doc/books/book">
<x:out select="$n/title" />
<br>
<x:out select="$n/author" />
<br>
========
<br>
</x:forEach>
</body>
</html>
-------------------------------------------
==========================
cobol
roy
==========
java
herbert
==========
c++
robert
==========
coldfusion
allaire
==========
xml unleashed
morrison
==========
jrun
allaire
==========
***********************************************
demo2.jsp
<html>
<body>
<c:import url="books.xml" var="url" />
<x:parse xml="${url}" var="doc" />
<table border=1>
<th>
<tr>
<td>title</td>
<td>author</td>
</tr>
</th>
<x:forEach var="n"
select="$doc/books/book">
<td>
<tr> <x:out select="$n/title" /></tr>
<tr> <x:out select="$n/author" /></tr>
</td>
</x:forEach>
</table>
</body>
</html>
title author
cobol roy
java herbert
c++ robert
coldfusion allaire
xml unleashed morrison
jrun allaire
------------------------------------------------
demo3 deals with the selection of particular book's author from the xml file ,when we
give the title, with the help of <x:if> action tag.The title is choosen from combo box in
demo2.htm file and submitted.We get a display of the selected title and its author.
--------------------------------------------------
demo3.htm
<html>
<body>
SELECT THE TITLE.<BR>
YOU WILL GET TITLE & AUTHOR.
<form method=post action="demo3.jsp">
<select name="combo1">
<option value="xml unleashed">xml
<option value="c++">c++
<option value="coldfusion">cold fusion
<option value="java">java
<option value="cobol">cobol
</select>
<input type=submit>
</form>
</body>
</html>
--------------------------
demo3.jsp
<html>
<body>
<c:import url="books.xml" var="url" />
<x:parse xml="${url}" var="doc" />
<c:set var="s" value="${param.combo1}"/>
------
<x:forEach var="n" select="$doc/books/book" >
<x:if select="$n/title=$s" >
<x:out select="$n/title" />
<br>
<x:out select="$n/author" />
<br>
</x:if>
</x:forEach>
</body>
</html>
-**********************************************
demo4 is a simple variation on the same theme. In this
case, the user selects the author name from the combo and
any books by that author are displayed, due to the code.
----------------------------------
demo4.htm
<html>
<body>
Select name of author & view his books<br>
<form method=post action="demo4.jsp">
<select name="combo1">
<option value="morrison">morrison
<option value="robert">robert
<option value="allaire">allaire
<option value="herbert">herbert
<option value="roy">roy
<option value="haris">haris
</select>
<input type=submit>
</form>
</body>
</html>
==============
demo4.jsp
========
<html>
<body>
<c:import url="books.xml" var="url" />
<x:parse xml="${url}" var="doc" />
<c:set var="s" value="${param.combo1}"/>
<x:forEach var="n" select="$doc/books/book" >
===============================================
In demo5 also, we display the title & author for a given title, but we now use
<x:choose, <x:when logic. This is similar to <c:choose, <c:when & <c:otherwise logic in
the core library.
----------------------------------------------
demo5.htm
<html>
<body>
SELECT THE TITLE.<BR>
YOU WILL GET TITLE & AUTHOR.
<form method=post action="demo5.jsp">
<select name="combo1">
<option value="xml unleashed">xml
<option value="c++">c++
<option value="coldfusion">cold fusion
<option value="java">java
<option value="cobol">cobol
</select>
<input type=submit>
</form>
</body>
</html>
-----------
demo5.jsp
<html>
<body>
<c:import url="books.xml" var="url" />
<c:set var="s" value="${param.combo1}" />
<x:parse xml="${url}" var="doc" />
<x:forEach var="n" select="$doc/books/book">
<x:choose>
<x:when select="$n/title=$s">
<c:set var="m" value="ok" />
<x:out select="$n/title" />
</x:when>
<x:otherwise>
</x:otherwise>
</x:choose>
</x:forEach>
<c:if test="${m!='ok'}">
<c:out value="no such book"/>
</c:if>
</body>
</html>
Result
--------------------
title sent from user:
c++
--------------------
c++
robert
========================-
title sent from user:
VB
--------------------
no such records
***************************************
-----------------------------------------------
<%@ taglib prefix="c"
uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml"
%>
<c:import url="students.xml" var="url" />
<c:import url="xsl1.xsl" var="xsl" />
<x:transform xml="${url}" xslt="${xsl}" />
-----------------------------------------------
// students.xml
<?xml version="1.0"?>
<students>
<student>
<name>Thomas</name>
<place>Delhi</place>
<number>1111</number>
<mark>78</mark>
</student>
<student>
<name>David</name>
<place>Bombay</place>
<number>4444</number>
<mark>90</mark>
</student>
<student>
<name>Mathew</name>
<place>Bangalore</place>
<number>5555</number>
<mark>92</mark>
</student>
<student>
<name>John</name>
<place>Hyderabad</place>
<number>6666</number>
<mark>72</mark>
</student>
</students>
-----------------------------------------------
xsl1.xsl
=======
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Name</th>
<th>Place</th>
<th>Number</th>
<th>Mark</th>
</tr>
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of select="name"/> </td>
<td><xsl:value-of select="place"/> </td>
<td><xsl:value-of select="number"/> </td>
<td><xsl:value-of select="mark"/> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
---------------------------------------------
===============================================
In this fourth & last part of the tutorial on JSTL,the author deals with the 'sql' tags
in JSTL and shows how they greatly simplify simple database operations like
'select' queries. In another demo, common database operations like 'add','modify' ,
'delete' & 'verify'also are dealt with.
The Struts community has ordained that JSP should be strictly a 'view-technology', in the
Model-View-Controller Architecture. According to Struts philosophy, JSP should not deal
with Data-Accesss and such data access should be done by 'Model' components only.(
read 'beans'). JSTL , however, provides for sql tags, inspired by ColdFusion! ( please see
a very short tutorial on DB-Operations using ColdFusion' available in this issue as a
separate lesson. and compare JSTL code and CF code!).And , a few months back, the
editor of 'Java Lobby' magazine was all admiration for the absolutely nice features of
these sql tags, whatever, 'struts' may say! Just as EJB may be 'overkill', except for really
big Enterprise applications, Struts also may be an unnecessary complication for small
and medium level projects. In such cases, it is much more direct to provide for data
access by the JSP itself, but using JSTL 'sql' tags.We take up these 'sql' tags in this part of
the tutorial.
Let us begin with 'sql.htm'. It just provides a simple form with just a textarea & submit
button. Normally, queries by MIS department will be very complex and so we have
provided a textarea for the 'select' query.After filling up the query, it is submitted and the
corresponding query.jsp is invoked.
// query.htm
<html>
<body>
<form method=post action="query.jsp">
<textarea name='area1' rows=10 cols=30>
</textarea>
<input type=submit>
</form>
</body>
</html>
------------------------------------
query.jsp is given below. In the standard jdbc code,we begin by asking for the
availability of the driver. "jdbc.odbc.JdbcOdbcDriver". And then, we specify the URL of
the database as 'jdbc:odbc:telephone'.
<sql:setDataSource tag.
It has attributes for 'driver' and 'url'. We will refer to the database as 'db'. The next step
is to collect the query typed in area1 by the user.
is used for this purpose.We also check up whether the query typed by the user has indeed
been correctly received.
<br>
Next, the '<sql:query' tag, takes three attributes., such as, symbolic name:
var="query1" datasource="${db} sql="${s}
The query result is then displayed in table form.It should be possible to follow the code
now.In our example, we are having an Access db, with table1, having two fields, (name,
place). registered with ODBC.
// query.jsp
============
<%@ taglib prefix="c" %>uri="http://java.sun.com/jstl/core"
<%@ taglib prefix="sql" %> uri="http://java.sun.com/jstl/sql"
<html>
<body>
<sql:setDataSource var="db"
driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:dbdemo" />
<c:set var='s' value="${param.area1}" />
<c:out value="${s}" /> <br>
<sql:query var="query1" dataSource="${db}" sql="${s}" />
</sql:query>
<table border="1">
<c:forEach var="row" items="${query1.rows}" >
<tr>
<td> <c:out value="${row.name}" /></td>
<td> <c:out value="${row.place}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
===============================================
In JSTL , we have a separate sql tag known as '<sql:update' for 'add', 'modify' and
'remove' operations.
When we want to verify, we must use' <sql:query' tag, because, resultset will be
returned.
------------------
dbeditor.htm
<html>
<body bgcolor=lightgreen>
<form method=post action="dbeditor.jsp">
<input type=text name='text1'>name<br>
<input type=text name='text2'>number<br>
<input type=text name='text3'> criterion<br>
<select name=combo1>
<option value="add">add
<option value="delete">delete
<option value="modify">modify
<option value="verify">find
</select>
<br>
<input type=submit>
</body>
</html>
-------------------------------------------------
dbeditor.jsp
</c:forEach>
<c:if test="${n != 'OK'}" >
<c:out value="No such Records" />
</c:if>
</table>
</c:if>
</html>
<body>
====================