You are on page 1of 94

JavaTM Education & Technology Services

Advanced Java Server Pages


(JSP)

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

Ch t 1
Chapter
Custom Tags

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

Chapter 1 Outline
What are the custom tags?
How to Write Custom Tags?
What is the TLD file?
The Tag Handler Life Cycle.
Using Custom tag in a JSP page.
The role of deployment descriptor.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

What are the custom tags?

They are special tags that are used to perform


customized actions
You can separate the presentation part of a JSP page
from the business rule implementation (Java code)
code).

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

What is wrong with java beans?

Only three action elementsjsp:useBean,


jsp:setProperty and getProperty
getProperty.
In some sit
situations,
ations we
e ha
have
e to resort to using
sing code in a
JSP page

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

What is the main idea of custom tags ?

JSP 1.1 defined a new feature: custom tags that can be


used to perform custom actions.
Custom tags -unlike java beans - have access to all the
objects available to JSP pages
pages, and custom tags can be
customized using attributes

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

How to Write Custom Tags?

There are mainly 4 steps


1-Design our own Custom Tag
2- Create a TLD file named taglib.tld, and save it in
the WEB-INF directory.
3 Compile,
3C
il and
d deploy
d l the
th Java
J
class
l
(your
(
tag
t
Handler).
4 Create a JSP file
4-Create
file, import your custom tag then
use it.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

The deployment descriptor,JSP,and TLD file.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

What is the TLD file?

A tag library descriptor (TLD) file is an XML document


that defines a tag library and its tags. A TLD file is to
custom tag handlers what a Web deployment descriptor
is to servlets.
A TLD file contains the <taglib> root element
element. This
element can have the following subelements:

tlibversion
jspversion
shortname
i f
info
uri
tag
JavaTM Education & Technology Services

Copyright Information Technology Institute

http://jets.iti.gov.eg

TLD file Elements

Th
The tlibversion
tlib
i element
l
t specifies
ifi th
the version
i number
b off
the tag library in the following format:
([0-9])* (("." [0-9])? (("." [0-9])? (("." [0-9])?
([0-9])

The shortname element specifies a short name for the tag library.
The value for this element must begin with a letter and must not
contain blank space.

The info element contains the information used for documentation


purposes Its default value is an empty string
purposes.
string.

The uri element specifies the link to an additional source of


documentation for the tag library.

The tag element is the most important element in a tag library. You can
specify more than one tag element in the same TLD file.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

10

Tag sub elements


Name (mandatory): specifies an identifier for the tag.
Tagclass
T
l
(mandatory):
(
d t
) specifies
ifi the
th fully
f ll qualified
lifi d name off
the Java class that handles the processing of this tag.
Teiclass : specifies
p
the helper
p class for this tag,
g, if there is
one
Bodycontent: specifies the type of the body content of the
tag if any
tag,
any. A body content is what appears between the
opening and closing tags. This element can have one of the
following values: empty, JSP, or tag dependent
Info: contains an informational description.
Attribute : specifies zero or more attributes. The attribute
element can have three subelements: name, required, and
rtexprvalue. Only name is a required subelement of the
attribute
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

11

Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP
Tag
Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/webjsptaglibrary_1_1.dtd">
p j
j
j p g
y_ _
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1 1</jspversion>
<jspversion>1.1</jspversion>
<shortname></shortname>
<tag>
<name>myTag</name>
<tagclass>mylibrary.MyCustomTag</tagclass>
</tag>
</taglib>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

12

What is Tag Handler ?

IIs the
h Java
J
class
l
that
h is
i linked
li k d to a custom tag and
d gets
invoked every time the JSP container encounters the custom
tag. The tag handler is so named because it handles the
processing of the tag
The tag handler must implement an interface in the
javax servlet jsp tagext package or extend one of the classes in
javax.servlet.jsp.tagext
the same package.
The most important interfaces are :
Tag
Iteration Tag
Body Tag

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

13

The Tag Interface

Contains
C t i th
the ffollowing
ll i methods
th d
doStartTag
doEndTag
d E dT
getParent
setParent
setPageContext
release
NB:
doStartTag
g return integers
g
which could be SKIP_BODY,,
EVAL_BODY_INCLUDE.
doEndTag return integers which could be SKIP_PAGE,
and EVAL_PAGE
EVAL PAGE
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

14

Example
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class BasicTagHandler
p
g
implements
p
Tag
g{
public void setParent(Tag t) {
}
public void setPageContext(PageContext p) {
}
public void release() {
}
public Tag getParent() {
return null;
}
public
bli iintt d
doStartTag()
St tT () {
return EVAL_BODY_INCLUDE;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

15

The Tag Handler Life Cycle

1. The JSP container obtains an instance of the tag


handler from the pool or creates a new one. It then
calls the setPageContext
setPageContext, passing a PageContext
object representing the JSP page where the custom tag
is found.
2. The
e JS
JSP co
container
a e then
e ca
calls
s the
e se
setParent
a e method.
e od
This method passes a tag object, which represents the
closest tag enclosing the current tag handler.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

16

The Tag Handler Life Cycle (contd)


3.The JSP container then sets all the attributes in the
custom tag
tag, if any.
any Attributes are handled like
properties in a JavaBean, namely by using the getter
and setter methods.
4. Next, the JSP container calls the doStartTag.
5. Regardless
g
of the return value of the doStartTag
g
method, the JSP container next calls the doEndTag
method.
6. The release method is the last method that the JSP
container calls.
7. The
Th JSP container
i
returns the
h iinstance off the
h tag
handler to a pool for future use.
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

17

Using Custom tag in a JSP page

you first
fi t need
d to
t use a taglib
t lib di
directive
ti iin your page.
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix"
%>
The uri attribute specifies an absolute or relative URI
that uniquely
q y identifies the tag
g library
y descriptor
p
associated with this prefix
Next to use it :
<prefix:tagName/>
fi
N
/
<prefix:tagName>body</prefix:tagName>
<m:myTag
<
T number="12"
b "12" power="13"/>
"13"/>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

18

The role of deployment descriptor

The JSP container can find the name and location of the
TLD file by looking up the deployment descriptor
This
Thi is
i preferable
f bl but
b t nott obligatory
bli t
Example:
<taglib>
t lib
<taglib-uri> /myTld</taglib-uri>
<taglib-location>/WEB-INF/taglib.tld
<taglib location>/WEB INF/taglib tld </taglib
</taglib-location>
location>

</taglib>
<%@ taglib uri="/myTld"
uri= /myTld prefix=
prefix="easy"%>
easy %>
<easy:myTag/>
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

19

Complete Example

The tag handler will take the form:


public class DoublerTag
p
g implements
p
Tag
g{
private int number;
public void setNumber(int number) {
this.number = number;}}
PageContext pageContext;
public void setParent(Tag t) {}
public void setPageContext(PageContext p) {
pageContext = p;}
public void release() {}
public Tag getParent() {return null;}
public int doStartTag()
S
() {{try {
JspWriter out = pageContext.getOut();
out.println("Double of " + number + " is " + (2 * number));}
catch(Exception
t h(E
ti e)) {}
return EVAL_BODY_INCLUDE;
}public int doEndTag() throws JspException {
return EVAL
EVAL_PAGE;}
PAGE;}
JavaTM Education & Technology Services

Copyright Information Technology Institute

http://jets.iti.gov.eg

20

Complete Example (contd)

The TLD file should take the form


<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN"
"htt //j
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
/j2 /dtd / b j t lib
1 1 dtd"
<taglib>
<tlibversion>1.0</tlibversion><>
< h t
<shortname></shortname>
></ h t
>
<tag>
<name>myTag</name>
<tagclass>mylibrary DoublerTag</tagclass>
<tagclass>mylibrary.DoublerTag</tagclass>
<attribute>
<name>number</name>
<required>true</required>
</attribute>
</tag>
</taglib>
/taglib
JavaTM Education & Technology Services

Copyright Information Technology Institute

http://jets.iti.gov.eg

21

Complete Example (contd)

The jsp page should include:


<%@ taglib uri="/WEB-INF/myTLD.tld"
prefix=JETS"%>
fi JETS"%>
<JETS:myTag number="12"/>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

22

The IterationTag Interface

The IterationTag interface extends the Tag interface.


It adds a new method called doAfterBody and a static
fi l integer
final
i t
EVAL_BODY_AGAIN.
EVAL BODY AGAIN
This method is invoked after the doStartTag method and
can return either the Tag
Tag.SKIP_BODY
SKIP BODY or
IterationTag.EVAL_BODY_AGAIN.
If the latter is returned,
returned the doAfterBody is called again
again. If
the return value is Tag.SKIP_BODY, the body will be
skipped
pp and the JSP container will call the doEndTag
g
method.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

23

Example
public class PowerTag implements IterationTag {
PageContext pageContext;
private int number;
private int power;
private int counter;
private int result = 1;
public void setNumber(int number) {
this.number = number;}
public
bli void
id setPower(int
tP
(i t power)) {
this.power = power;}
public void setParent(Tag t) {}
public void setPageContext(PageContext p) {
pageContext = p;}
public void release()
p
() {}
public Tag getParent() {
return null;}
public int doStartTag() {
return EVAL_BODY_INCLUDE;}
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

24

Example (contd)
public int doAfterBody() {
counter++;
result *= number;
if (counter == power)
return SKIP_BODY;
SKIP BODY;
else
return EVAL_BODY_AGAIN;}
EVAL BODY AGAIN;}
public int doEndTag() throws JspException {
System.out.println("doEndTag");
try {
JspWriter out = pageContext.getOut();
out println(number + "^"
out.println(number
^ + power + "="
= + result);}
catch(Exception e) {}
return EVAL_PAGE;}}
EVAL PAGE;}}
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

25

Example (contd)
The jsp should take the form :
<%@ taglib uri="/myTLD" prefix="easy"%>
<easy:myTag number="2"
number= 2 power=
power="3">
3 > </easy:myTag >

The tld should take the form :

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
tlibversion 1.0 /tlibversion
<shortname></shortname>
<tag>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

26

Example (contd)
<name>myTag</name>
<tagclass>mypackage PowerTag</tagclass>
<tagclass>mypackage.PowerTag</tagclass>
<attribute>
<name>number</name>
name number /name
<required>true</required>
</attribute>
<attribute>
<name>power</name>
<required>true</required>
</attribute>
</tag>
</taglib>
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

27

To manipulate body content

A JSP custom
t
tag
t can have
h
a body
b d content,
t t such
h as the
th
following tag:
<%@ taglib uri="/myTLD"
uri= /myTLD prefix=
prefix="x"%>
x %>
<x:theTag>This is the body content</x:theTag>
When you use the Tag and IterationTag interfaces, you
cannot manipulate the body content. You don't even
have access to it.
This
Thi could
ld b
be achieved
hi
db
by:
The BodyTag Interface
The
Th BodyContent
B d C t t Class
Cl

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

28

To manipulate body content (contd)


BodyTag interface has a similar life cycle of IterationTag
interface.
The difference is that the doStartTag method of the tag
handler implementing BodyTag can return
SKIP_BODY,
SKIP BODY EVAL_BODY_INCLUDE,
EVAL BODY INCLUDE or
EVAL_BODY_BUFFERED.
If the method returns EVAL_BODY_INCLUDE,
EVAL BODY INCLUDE the
body is evaluated as it is in IterationTag. If the method
returns EVAL_BODY_BUFFERED, a BodyContent
object
bj t is
i created
t d that
th t represents
t the
th custom
t
tag's
t '
body content
Two extra methods are called by the JSP container in
tag handlers implementing the BodyTag interface:
setBodyContent and doInitBody.
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

29

The Support Classes

The TagSupport Class


Implements
p
the IterationTag
g interface

The BodyTagSupport Class


Extends
E t d TagSupport
T S
t implements
i l
t BodyTag
B d T
interface

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

30

Example
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public
bli class
l
C
CapitalizerTag
it li T extends
t d B
BodyTagSupport
d T S
t{
public int doAfterBody() {
String content = bodyContent.getString();
bodyContent getString();
try{
p
out = bodyContent.getEnclosingWriter();
y
g
g
()
JspWriter
out.print(content.toUpperCase());
}
catch(Exception
t h(E
ti e)) {}
return SKIP_BODY;
}
}

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

31

Lab Exercise

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

32

Assignment

Create your own custom tag , and use in


your jjsp
p
in y

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

33

Ch t 2
Chapter
JSTL

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

34

Chapter 2 Outline

What is JSTL ?
JSTL main packages.
Core Package
JSP Expression Language
Database Package.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

35

What is JSTL ?

It stands for JSP Standard


Tag Library
What do we need to run
JSTL ?
What is wrong with JSP?

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

36

How does JSTL fix JSP problems?

JSTL ttags are XML


XML, th
they cleanly
l
l and
d uniformly
if
l bl
blend
d

into a page's HTML markup tags.


The main JSTL tag libraries include most functionality
that would be needed in a JSP page.
JSTL tags are easier for non-programmers and
inexperienced programmers to use effectively
effectively, because
they do not require any knowledge of programming or
Java.
JSTL ttags can reference
f
objects
bj t iin th
the requestt and
d
session without knowing the object's type and no casting
is required.
JSP's EL (Expression Language) makes it easy to call
getter and setter methods on Java objects.
JavaTM Education & Technology Services

Copyright Information Technology Institute

http://jets.iti.gov.eg

37

The relation between JSP and JSTL

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

38

JSTL main packages

Plus the function package which is a set of


standardized EL functions.
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

39

JSTL main packages (Contd)


The core library includes tags for the following uses:
Accessing and modifying data in memory
Making decisions in your pages
Looping over data

The
e XML library
b a y includes
c udes tags for
o tthe
e following
o o
g pu
purposes:
poses
Parsing (that is, reading) XML documents
Printing parts of XML documents
Making decisions in your page based on the contents of an XML
document

The formatting and internationalization library includes


tags for these uses:
Reading and printing numbers
Reading and printing dates (with support for time zones)
Helping your application work with more than one language

The SQL library helps you read and write data from
databases
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

40

How to introduce those packages in your


code?

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

41

Core Package

It depends mainly on
p
Language
g g
Expression

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

42

Expression Language
How Expression Language looks like ?
It starts
t t with
ith ${
Example :

and
d ends
d with
ith }

${ 1+2}

NB: Expression Language can be understood


inside JSTL Tags and JSP tags as well
well.
Types of data read by EL?
Scoped Variables
Request Parameters

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

43

What are scoped variable?


What are types of scoped variables?
strings, numbers , booleans and collections which could
be arrays

How EL reads Scoped Variables?


${ username }
${user.phone}
$
${header["User-Agent"]}

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

44

Expression Language (contd)


The default of scopes: Page-request-session then finally
application
To be able to specify your variable scope :

${pageScope.username}
${p
g
p
}
${requestScope.username}
${sessionScope.username}
${applicationScope.username}

Example:
${sessionScope.shopping-Cart[0]}
${sessionScope shopping Cart[0]}
${sessionScope.shoppingCart[1]}

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

45

How to read request parameters?


Simply by :
${param.name}
${param name}
${paramValues.name}

Example
<p>Wow, I know a lot about you...</p>
<p>Your name is ${param.username}/>.</p>
${param.username}/> </p>
<p>Your password is ${param.pw}/>.</p>
p
are ${p
${param.gender}/>.</p>
g
}
p
<p>You

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

46

Accessing other data with EL

Implicit Objects supported by JSTL

cookie:
ki JSTL d
doesnt
t give
i you a way tto sett cookies
ki
(backend job) but u can retrieve cookies.
header: read all client header
headerValues: all values
initParam: to access initialization parameters
pageContext: more details about your page

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

47

Page Context elements

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

48

Page Context elements

(contd)

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

49

Mathematical operators supported by EL

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

50

Comparisons supported by EL

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

51

Comparisons supported by EL

(contd)

Take care : ${ } must include the entire expression.


E
Example
l off iinvalid
lid statments:
t t
t
${ ${user.weight} gt ${user.IQ} }
${user.weight}
${user weight} gt ${user
${user.IQ}
IQ}
Only we can say :
${user.weight
${user weight gt user.IQ}
user IQ}

Boolean operations and parentheses


${ (param.month == 5 or param.month == 6) and
(param.day == 25) }

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

52

To check if a certain parameter exists?


Use the keyword : empty
Example:
${empty param.choice}
${empty sessionScope.userName}

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

53

Core Package

(cont.)

Now back to core package.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

54

<c:out>
Used for printing results of expressions
Example:
<c:out value="Hi, there!"/>
<c:out
c:out value
value="${username}"
${username} default
default="Nobody"/>
Nobody /
<c:out value="${username}">
Nothing

</c:out>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

55

<c:set>
Used mainly to create scoped variables
Example:
p
<c:set var="four" value="${3 + 1}"/>
<c:set var="four" scope="session" value="${3 +

1}"/>

<c:set var="eight">
<c:outt value="${4
l
"${4 * 2}"/>
2}"/
</c:set>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

56

<c:remove >
Used to delete data
Example:
E
l
<c:remove var="doomed" scope="session"/>
Unlike other jstl tags , it will not propagate across
scopes if not found.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

57

<c:catch >

This action allows you to catch an error in your page,

<c:catch var="numException">
<jsp:scriptlet>int zero = 0;
out.write(3/zero);</jsp:scriptlet>
</c:catch>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

58

Controlling flow with conditions


<c:if>
The <c:if> tag evaluates its test attribute, and if this
expression evaluates to false
false, the page skips the
body of the <c:if> tag. On the other hand, if the
expression
p
ends up
p being
g true.
The body is processed normally. This body can
contain any valid JSP code, including text, HTML
tags or other JSP tags
tags,
tags.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

59

<c:if>

(contd)

You can use <c:if> tags anywhere in your pageeven


in the middle of an HTML tag.
Example:
<font size="2"
< if test="${user.education==doctorate}">
<c:if
t t "${
d
ti
d t t }">
color="red"
</c:if>
/c:if
<c:out value="${user.name}"/>
</font>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

60

Nested <c:if> tags

Example:
<c:if test="${fatalError}">
Im sorry,
I
<c:if test="${user.education==doctorate}">
Dr.
Dr
</c:if>
<c:out value=
value="${user
${user.name}
name}"/>
/>,
but you have committed a fatal error.
</c:if>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

61

Complex conditional tags


Mutually exclusive conditions with
<c:choose> <c:when> and <c:otherwise> .
<c:choose>,<c:when>,
similar to switch statements
The <c:choose>
c:choose tag is simple: it takes no attributes
and serves only as a container
for <c:when> and <c:otherwise> tags.
g Just as HTMLs
<td> tag makes no sense outside a <table>,
<c:when> and <c:otherwise> make no sense outside
a <c:choose>.
h

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

62

Complex conditional tags (contd)

The <c:when> tag is similar to <c:if>: it takes a single


test attribute.
For each <c:choose> tag, no more than one child
<c:when> tag can succeed
succeed.
<c:otherwise> succeeds only if all its sibling <c:when>
tags (those with the same parent <c:choose> tag) have
failed.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

63

Example
<c:choose>
<c:when test="${num==2}">
<li>Error 1 has occurred.</li>
</c:when>
<c:when test=
test="${num==3}">
${num==3} >
<li>Error 2 has occurred.</li>
</c:when>
<c:when test="${num==4}">
<li>Error 3 has occurred.</li>
</c:when>
<c:otherwise>
<li>Everything is fine.</li>
</c:otherwise>
/
h
i
</c:choose>
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

64

Rules for using the complex conditional tags

1 <c:when>
1h
and
d <c:otherwise>
th
i
ttags cannott appear
outside a <c:choose> tag.
2- There
Theres
s a flip side to this rule: a <c:choose> tag cannot
have any direct children (or nonwhite space text) except
<c:when> or <c:otherwise> tags.
3- If <c:otherwise> occurs, it must follow all the <c:when>
tags; it may not come before any of them.
4 Every <c:choose> must have at least one <c:when> and
4no more than one <c:otherwise>.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

65

Example on Invalid Syntax

<c:choose>
<p> hiiiiiiiiiiiiiiiiiii </p>
<c:when> </c:when>
<c:otherwise> </c:otherwise>
</c:choose>
<c:choose>
<c:otherwise> </c:otherwise>
<c:when> </c:when>
</c:choose>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

66

Controlling flow with loops <c:forEach>

lets you loop over nearly any sensible collection of items that the
expression language returns
Example:
<c:forEach items="${user.medicalConditions}" var="ailment">
<c:out value=
value="${ailment}"/>
${ailment} />
</c:forEach>

<c:forEach> accepts:

Arrays
Collection variables (including Lists and Sets),
Maps, Iterators, and Enumerations.
simple strings.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

67

Iterating over strings with <c:forTokens>


We can parse strings as follows
<c:forTokens
f T k
items="a,,b,,c"
it
" b " delims=",">
d li
""
<c:forTokens items="a,;,b,;,c" delims=",;">
<c:forEach > can be used with comma delimeter only:
<c:forEach items="a,b,c">

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

68

Advanced usage for iteration tags <c:forEach>


and <c:forTokens>.

you can determine information about the current items


position within the overall loop: is it first, last, or
somewhere in the middle?
You can loop over only a part of collection using index

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

69

Example

<c:forTokens items="a,b,c,d,e,f" delims=","


var="letter" begin="4">
<
<c:out
t value="${letter}"/>
l
"${l tt }"/>
</c:forTokens>
<c:forEach
f E h begin="1"
b i "1" end="5"
d "5" var="current">
"
t"
<c:out value="${current}"/>
</c:forEach>
/ f E h
<c:forEach begin="1" end="50">&nbsp;</c:forEach>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

70

Advanced usage for iteration tags <c:forEach>


and <c:forTokens> (contd)

Looping tags also support a varStatus attribute that


lets you recover information about where you are in
the overall iteration

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

71

<c:import>

It supercedes <jsp: include>, providing all the


functionality of the core JSP tag but also adding new
features lets you store the retrieved text in a scoped
features,
variable instead of printing it.

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

72

Example

<c:import url="target.jsp"/>
<c:import url="http://www.cnn.com"/>
You can retrieve files from another web application
by specifying that web applications name using the
<c:import>
i
t tags
t context
t t attribute
tt ib t .

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

73

Communicating with imported pages

The <c:param> tag is used to send parameters to the

requested page

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

74

<c:redirect>

To redirect to another resource


<c:redirect url="newPage.jsp"/>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

75

Database Package

We have to use :
<%@ taglib prefix="sql"

uri="http://java.sun.com/jstl/sql"
i "htt //j
/j tl/ l" %>
Should
Sh ld we use JSP tto connectt to
t database?
d t b
?
When
Wh to use d
database
b
iin JSP ?

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

76

Two architectures are available

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

77

<sql:setDataSource>

Setting up a database connection


you can decide to expose a scoped variable that
represents
t the
th database
d t b

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

78

Example

<sql:setDataSource
driver=jdbc.odbc.jdbcDriver"
url="jdbc:odbc:dsn2"
user=jstl password=iti"
var="databaseOne"
scope="session" />
<sql:setDataSource
dataSource="${databaseOne}"
scope="request" />

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

79

<sql:query>

Used to perform queries with

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

80

Example

<sql:query var="result">
SELECT * FROM CUSTOMERS
</sql:query>
<sql:query var="result" sql="SELECT * FROM
CUSTOMERS"/>
CUSTOMERS"/

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

81

<sql:query> (contd)

Accessing
A
i metadata
t d t : u can gett column
l
names and
d row
count through rowCount, columnNames attributes .
Example:
<sql:query var="smartUsers">
SELECT NAME, IQ FROM USERS WHERE IQ > 120
</sql:query>
<table>
<c:forEach items="${smartUsers.rows}" var="row">
<tr>
tr
<td><c:out value="${row.NAME}"/></td>
<td><c:out value="${row.IQ}"/></td>
</tr>
</c:forEach>
</table>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

82

Examples

<c:forEach items="${requestScope
items="${requestScope.result.rowsByIndex}
result rowsByIndex} var="row
var="row
varStatus="s">
<c:if test="${s.first}">
<table>
<tr> <c:forEach items="${requestScope.result.columnNames}
var="col">
<th><c:out value="${col}"/></th>
value= ${col} /></th>
</c:forEach> </tr>
</c:if>
<tr>
t <c:forEach
f E h items="${row}"
it
"${
}" var="value">
" l "
<td><c:out value="${value}"/></td>
</c:forEach> </tr>
<c:if test="${s.last}">
</table>
</c:if>
</c:forEach>
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

83

<sql:param>

Example

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

84

Formatting and internationalization


Package

Import it using :

<%@ taglib prefix=fmt"


uri="http://java.sun.com/jstl/fmt" %>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

85

<fmt:formatNumber>
Used to Printing numbers
Differ than <c:out>:
Provide some control on how numbers are printed
<fmt:formatNumber>
fmt:formatNumber tag can automatically sense the
browser locale and customize its output.
Example:
<fmt:formatNumber value="${netWorth}"/>
The output would be:
United States 500,000.01
France 500 000,01
Germany
G
500 000 01
500.000,01
Switzerland 500'000.01
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

86

<fmt:formatNumber> attributes

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

87

<fmt:formatDate>

Used to print date


Example
United States May 20, 2002
France 20 mai 2002
Germany 20.05.2002
Netherlands 20-mei-2002
Spain 20-may-2002

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

88

<fmt:parseNumber>

Useful only if you need to retrieve a numeric value from


a string

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

89

<fmt:parseDate>

Useful to convert a string to a date format

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

90

<fmt:setLocale>

Used to override locales

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

91

List of different Locales

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

92

Resource bundles

To define a collection of files used for internationalize


your website
<fmt:bundle>
<f t b dl >
<fmt:setBundle>

JavaTM Education & Technology Services


Copyright Information Technology Institute

http://jets.iti.gov.eg

93

References & Recommended Reading

Core servlets and JSP


Java for the Web with Servlets, JSP, and EJB
Manning JSTL in Action
Sun presentations
Oracle presentations
SCJWD study guide
JavaTM Education & Technology Services
Copyright Information Technology Institute

http://jets.iti.gov.eg

94

You might also like