Академический Документы
Профессиональный Документы
Культура Документы
1
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.
==============================================
[It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in
Tomcat environment. In case of any difficulty, they can refer to back issues of this magazine ( from Oct-2003
onwards) and gain access to a number of lessons for illustrations.]
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.
-----------------------------------------------
We begin with a simple html form;
// greeting.htm
=============
<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();
2
//-------------------------------
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>
-----------------------------------------------
Some coders prefer to use expressions.
What is an 'expression'? It is a method of sustituting request-time values in html page. ( see greeting2.jsp).
Carefully note that there is no semi-colon after ("text1").
----------------------------------------------- // greeting2.jsp
<html>
<body bgcolor=yellow>
we welcome <br>
<%= request.getParameter("text1") %>
</body>
</html>
-----------------------------------------------
The third variant is to use a javabean to encapsulate the business-logic. We develop a jsp-bean as follows:
------------------------------------------
// greeter.java
//==============
package ourbeans;
3
public class greeter {
public greeter() { }
public String greetme(String s) {
return "we welcome..."+s;
}
}
-------------------------------------------
This source file is compiled and the class-file is copied to :
'e:\tomcat5\webapps\root\WEB-INF\classes\ourbeans'
4
==================================
With these brief hints, it should not be difficult to understand the
following JSP page written by using JSTL core-tags.
-----------------------------------------------
// greeting4.jsp ( uses JSTL)
===========
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<body>
<c:set var=s value="${param.text1}" />
We welcome<br>
<c:out value="${s}" />
</body>
</html>
-----------------------------------------------
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.
They are as follows:
1) core
2) xml
3) sql
4) formatting
5) functions.
----------------------------------------------- The most difficult part is to set up Tomcat so that it executes JSTL.
There are some basic requirements, before we can experiment and study the use of JSTL.All that we have
studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not
built into Tomcat5 even, as yet.
Without hands-on experimention, JSTL could be confusing and strange,because of the fact that it is very
recent . But in coming months, support will be built into Tomcat and we won't have to worry about installing
the JSTL libraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development
environment..
So , how do we go about , placing the JSTL libraries in tomcat?
------------------------------------------------ The best solution is to get JWSDP1.3.
This is Java Web Service Development' Pack.
( Carefully note the version , however!).
It is good to start with this because, it contains a lot of valuable software , including the latest and greatest
from JCP, (ie) JSF
(Java Server Faces).... which may soon replace Struts.
5
We unzip the jwsdp1.3 and install it in C: drive. There are a number of folders like JAXP, JAXR,
JAXB,JAX-RPC, JSF, JSTL etc. in the JWSDP pack.
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
d) tld ( tag library descriptors)
When we look into the 'lib' folder, we find two jar files:
a) standard.jar
b) jstl.jar
We should copy these two jar files into :
'e:\tomcat5\webapps\root\WEB-INF\lib'
-----------------------------------------------
( Remember to restart the Tomcat server). That is all that is required to use JSTL. !
The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are already
included in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is
restarted.
***********************************************
( we are using tomcat5 & jdk1.4.2)
( 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)
sql.tld & (sql)
fn.tld. (functions)
------------------------------
Some authors say that we should copy these tld files to ..
..:\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 !
We found that the programs works well. No problem!
When we study the web.xml file in e:\tomcat\webapps\root\WEB-INF folder, we find that it follows DTD
and not Schema.
( DTD stands for Document -Type- Definition).
6
( 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 next part of this tutorial, we study the tags available in the JSTL-core library.
PART-2 -CORE TAGS IN JSTL
Tutorial Home | Part 1 | Part 2 | Part 3 | Part 4
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.
We are now ready to experiment with all the tags in the ‘core’ library. The core tags have the following
uniform ‘uri’.
‘http://java.sun.com/jstl/core'
( However, in the book by Hans Bergsten titled,"Java Server Pages" ( third edition),
(OReilly pub)the uri is consistently given as :
'http://java.sun.com/jsp/jstl/core'.It looks as if there has been some change in specification and grammar, after
it was published!
This appears to be wrong as the server threw exception.The correct uri is :
'http://java.sun.com/jstl/core'.)
The prefix is ‘c:’
The following tags are available in the ‘core’ library.
( Remember them as a dozen!).
<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
-----------------------------------------------
We will now see simplest illustrations for the above tags.There are a dozen demos, to bring out the features of
each of these tags.
---------------------------------------
demo1.jsp uses <c:set & <c:out tags.
:We create demo1.jsp as:
e:\tomcat5\webapps\root\demo1.jsp
-----------------------------------------
7
// demo1.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<body bgcolor=lightblue>
<form method=post action="demo1.jsp">
NAME <input type=text name="text1"><br>
PLACE<input type=text name="text2"><br>
<input type=submit>
</form>
NAME:<c:out value="${param.text1}" /><br>
PLACE:<c:out value="${param.text2}" />
</body>
</html>
----------------------------------------------
In all the previous examples, we invoked the JSP file through a html file. But, in demo1.jsp, we are posting
the page to itself.( in asp.net style!).( but there is no 'retention of data' , unlike asp.net).
We start Tomcat5, and type the url as :
‘http://localhost:8080/demo1.jsp’. in the browser.We get a form with two text boxes and a submit button. We
fill up the textboxes with ‘name’ and ‘place’ and submit.
The demo1.jsp executes and displays the values entered by the user.due to the JSTL tags
<c:out value=”${param.text1} /> etc.
That is about our first and introductory example.
----------- ---
The second example is very important. When the user enters data in a number of fields, it is tedious to
collect the data and transfer it to jsp page for processing. In our example, we are collecting data about a player,
such as his name, place and game. We can have much more but we are restricting for space considerations.
JSP has an action tag , known as 'jsp:setProperty'. Using this along with a standard javabean, we can extract
data and transfer it to our program in a single step.
The syntax is
<jsp:useBean
id="bean1" class="ourbeans.player" >
<jsp:setProperty
name="bean1" property="*" />
</jsp:useBean>
:( the * sign denotes 'all').
-----
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;
8
public player(){
name=" ";
place=" ";
game=" ";
}
//---------------------------
public void setName(String a){
name=a;
}
public void setPlace(String b){
place=b;
}
public void setGame(String c){
game=c;
}
//------------------------------
public String getName(){
return name;
}
public String getPlace(){
return place;
}
public String getGame(){
return game;
}
}
---------------------------------
In demo2.jsp, we collect the data and then display the data entered by the user.
Note that instead of {param.text1}, we are using {bean1.name}. We should carefully name the html form
controls with the corresponding attribute names given in the bean. We cannot name the controls as 'text1' etc,
now!
<c:out value="${bean1.name}" />
<c:out value="${bean1.place}" />
<c:out value="${bean1.game}" />
---
We get correct result.
=============================================
// demo2.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c"
uri="http://java.sun.com/jstl/core" %>
<html>
<body>
<form method=post action="demo2.jsp">
<jsp:useBean id="bean1" class="ourbeans.player">
9
<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>
Name: <c:out value="${bean1.name}" /><br>
Place: <c:out value="${bean1.place}" /><br>
Game: <c:out value="${bean1.game}" />
</body>
</html>
=============================================
Once again, it will be noticed that there is no java code in this example, as everything is being done by tags,
only..
***********************************************
We are now ready to take up examples for 'condition' tags.
There are two types of 'condition tags'.
namely, <c:if> & <c:choose>.
In the third demo, we learn how to use the <c:if tag.
----------------------------------------------
//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>
<c:if test="${s eq 'sam' }" >
<c:out value="Good Morning...SAM!" />
</c:if>
<c:if test="${s = = 'tom'}" >
<c:out value=" How Are You?....TOM!" />
</c:if>
</body>
</html>
-----------------------------------------
10
There is a combo with two options, namely
'sam' and 'tom'. If the user selects 'sam' and submits the form, he gets 'GoodMorning ...SAM!". If he selects
'tom' instead, he gets
'How are you..TOM?'.
The above code is no ‘Rocket-Science’ as American authors say!But , if we are careless in typing the names
‘sam’ or ‘tom’ in the test condition, we could spend hours together , trying to coax this code into functioning!
We should not leave space after the single quote in the 'test expression'. Second point worth noting in the
above example is that we can use either == ( double equal to) or eq to test equality.
***********************************************
In the fourth example which follows, we take up <c:choose> tag.
The syntax is:
<c:choose >
<c:when test=" " >
<c:otherwise> something </c:otherwise>
</c:choose>
The peculiarity to be noted here is that unlike <c:if , where we had to explicitly use <c:out for printing , no
such <c:out has been used here., and yet the result is displayed,
because 'choose' includes 'displaying'..
When we choose '7', "select between 1 & 5 " will be displayed!
-----------------------------------------------
// 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>
<font size=24 color=red>
<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>
11
<c:when test="${s==5}">Thursday</c:when>
<c:otherwise>
select between 1 & 5
</c:otherwise>
</c:choose>
</body>
</html>
---------------------------------------------
Demo-5 deals with Iteration tag.
We are familiar with the 'for-each' construct.
JSTL's 'for-each' also has the same functionality.
In the following example, we have a String array. named as 'colors'.
By using the <c:forEach> tag, we iterate through the array and display the values.
------------------------------------
//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>
We get the following display, when we execute the program.
===============================================
<c:forEach> action tag contain the following attribute list:
items : the collection of items like String[]
var : a symbolic name for the collection
begin : the starting index of iteration
end : the ending index of iteration
12
step : incremental step
varStatus: symbolic name for current status.
If we assign the symbolic name 'a' for the status, we are able to access its properties such as index, count,
whether it is first item,
whether it is last item and the current value.
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
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="n" begin="3" end="8" >
<c:out value="${n}" /> <br>
</c:forEach>
3 4 5 6 7 8
===============================================
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>
13
------------------------------------------
------------------------------------------
The essential attributes of 'forTokens' tag are:
Attribute Description
items The string to tokenize
delims The delimiter characters that separate the tokens of the string.
===============================================
Demo8 deals with URL-Related actions.<c:import>action tag imports the conent of a URL-based resource and
provides a simple way to access URL-based resources that can either be included or processed within the JSP..
In the following example,the import action tag imports the content of welcome.htm file here.So it displays the
contents of demo8.jsp and welcome.htm.
--------------------------------------------
// 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!" />
===============================================
In demo9 we discuss the <c:url> action tag.
<c:url> prints the value of URL.It is easier to construct the hyperlinks.It is useful for session preservation
(URL-Encoding).
In the following example,we use <c:url> to make a link to another html file. When we execute demo9, we get
a link , with text 'send'.
When we click on the link, we are taken to welcome.htm.
--------------------------------------
demo9.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<a href="<c:url value="http://localhost:8080/welcome.htm/>">
send
</a>
--------------------------------------
14
===============================================
demo10 deals with <c:redirect> action tag.
This tag forwards the browser to the specified URL .
demo10.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:redirect
url="http://localhost:8080/welcome.htm />
===============================================
Finally, <c:param> tag is useful to send some parameter value to the page to which redirect occurs. In our
example, the code redirects to sample.jsp, but it takes the param named 'a'
with value='SAM' , to the redirected page.
And, the sample.jsp accepts this param and prints it. <c:out value="${param.name1}"/>
----------------------------------------------
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}"/>
And to end our whirlwind tour of core-tags in JSTL, here is a demo which mixes EL of JSP-2(Expression
Language of JSTL) with 'Expression' (also known as request-time Expression ) of JSP1.2.
demo12.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
JSTL welcomes <br>
<c:out value="${param.text1}" />
<br>
JSP Expression welcomes
<%=request.getParameter("text1") %>
-------------------------------------------
In the next and third part of this tutorial, we will learn about xml tags in JSTL.
16
<x:forEach var="n"
select="$doc/books/book">
is used to select the elements from the xml file.
<x:out select="$n/title" />
is used to print the elements of the xml file. We begin by importing the reference to the XML file to be
parsed.
<c:import url="books.xml" var="url" />
-----
We have given a symbolic name for this file as 'url'.Next we ask the program to parse this XML file.The
resulting tree is given a symbolic name as 'doc'.
<x:parse xml="${url}" var="doc" />
In the next step, we direct the program to select each title and each author in the XPATH expression
$doc/books/book. If we refer to the xml file , we find that the root element of the document is 'books'. Inside
this, we have 'book'.So, XPATH can be thought of as just a file hierarchy. Just like <c:out, we have <x:out!
demo1.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" >uri="http://java.sun.com/jstl/xml" %>
<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>
Magically, we have parsed a given XML document and extracted information, without any mention about
DOM,SAX and such words., atall!Wonderful!As a famous author would say, 'anything that makes my job
easier, I like!'.
When we execute the 'program', we get the following result.
-------------------------------------------
(Result for executing demo1.jsp)
==========================
cobol
roy
17
==========
java
herbert
==========
c++
robert
==========
coldfusion
allaire
==========
xml unleashed
morrison
==========
jrun
allaire
==========
***********************************************
The following program (demo2)displays the books and authors of xml file in table format.
demo2.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" >uri="http://java.sun.com/jstl/xml" %>
<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
18
c++ robert
coldfusion allaire
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.
Think of this as an sql query like
"select * from table1 where title='jrun'"
--------------------------------------------------
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
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>
<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>
19
<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.
It will be noted that 'allaire' has two books to his credit and so if we choose 'allaire' in the combo,his two
books are displayed.If 'haris' is chosen, we should display the message that it is yet to be published as there is
no such entry in the xml file. But there is no 'if-else' construct and so we improvise.
We have created a variable 'a' and assigned the value 'ok' to it. If there is no author to match the user's
selection, the conditional block is ignored and 'a' will not be 'ok'.
From this, we conclude that 'the book is not ready'.
----------------------------------
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
========
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>
<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/author=$s" >
<c:set var="a" value="ok" />
20
<x:out select="$n/title" />
<br>
<x:out select="$n/author" />
<br>
</x:if>
</x:forEach>
<c:if test="${a!='ok'}" />
<c:out value="not yet ready!" />
</c:if>
</body>
</html>
===============================================
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
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>
<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>
21
<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
***************************************
In demo6 , we see XSLtransform using JSTL. ( as promised in the earlier tutorial on XSLT in October
issue).For the sake of continuity with the earlier tutorial,we revert back to students.xml and xsl1.xsl, as given
in October issue. Just three lines and DONE!)
-----------------------------------------------
<%@ 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>
22
<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>
---------------------------------------------
23
Davi Bombay 4444 90
d
===============================================
That completes our study of 'xml' tags in JSTL.We now move ahead to the fourth and final part of the present
tutorial, dealing with 'sql' tags in JSTL.
25
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
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="c" 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='a' value='${param.text1}' />
<c:set var='b' value='${param.text2}' />
<c:set var='c' value='${param.text3}' />
<c:set var='d' value='${param.combo1}' />
----------------------------------------------
<c:if test="${d == 'add'}" >
<sql:update var="query1" dataSource="${db}"
sql="insert into table1 values${a}','${b}')" >
</sql:update>
<c:out value="record added"/>
</c:if>
---------------------------------------------
<c:if test="${d == 'delete'}" >
<sql:update var="query1" dataSource="${db}"
sql="delete from table1 where name='${a}'" >
</sql:update>
<c:out value="record deleted"/>
</c:if>
-------------------------------------------
<c:if test="${d == 'modify'}" >
<sql:update var="query1" dataSource="${db}"
sql="update table1 set table1.name='${a}',
table1.place='${b}' where
26
table1.name='${c}'" >
<--sql should be typed in a single line -->
</sql:update>
<c:out value="record modified"/>
</c:if>
------------------------------------------
<c:if test="${d == 'verify'}" >
<sql:query var="query1" dataSource="${db}"
sql="select * from table1 where name='${a}'" >
</sql:query>
<table border="1">
<c:forEach var="row" tems="${query1.rows}" >
<c:set var="n" value="OK" />
<tr>
<td> <c:out value="${row.name}" /></td>
<td> <c:out value="${row.place}" /></td>
</tr>
</c:forEach>
<c:if test="${n != 'OK'}" >
<c:out value="No such Records" />
</c:if>
</table>
</c:if>
</html>
<body>
====================
These are, afterall, the essentials. All else, are only, ornamental. Thus, it will be seen that the JCP has done a
great job in creating really fine standard tags, for simplifying routine tasks. But, Java coders, have to take note
that , their job as JSP coders, will be slowly eroded by page-authors using JSTL!
Suggested Reference Books
1) Pro JSP by
SIMON BROWN & OTHERS
(A-Press)
(Excellent material)
2) JavaServer Pages by
Hans Bergsten ( Third Edition)
(O'Reilly Press/SPD)
3) EARLY ADOPTER JSP Standard Tag Library by
JAYSON FALKNER & OTHERS
Wrox Press
4) JSTL in Action by
SHAWN BAYERN
(Manning/ DreamTech).
27