Advanced Java Server Pages (JSP)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

JavaTM Education & Technology Services

Advanced Java Server Pages


(JSP)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 1
Chapter 1

Custom Tags

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 2
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 3
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).

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 4
What is wrong with java beans?

• Only three action elements—jsp:useBean,

jsp:setProperty and getProperty.

• In some situations, we have to resort to using code in a


JSP page

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 5
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, and custom tags can be
customized using attributes

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 6
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, and deploy the Java class (your tag Handler).

4-Create a JSP file, import your custom tag then use it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 7
How to Write Custom Tags? (cont’d)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 8
The deployment descriptor,JSP,and TLD file.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 9
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. This
element can have the following subelements:
• tlibversion
• jspversion
• shortname
• info
• uri
• Tag*
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 10
TLD file Elements

• The tlibversion element specifies the version number of the tag library in the
following format:
([0-9])* ("." [0-9])? ("." [0-9])? ("." [0-9])?
1.1.1.1 , 22 , 2.3 , 3.3.6
• The jspversion element specifies the version number of JSP used.

• 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.

• 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 11
Tag sub elements

– Name (mandatory): specifies an identifier for the tag.

– Tagclass (mandatory): specifies the fully qualified name of the Java class
that handles the processing of this tag.

– Teiclass : specifies the helper class for this tag, if there is one.

– Bodycontent: specifies the type of the body content of the tag, if 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 12
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">

<taglib>
<tlibversion> 1.0 </tlibversion>
<jspversion> 2.0 </jspversion>
<shortname> Mytag </shortname>

<tag>
<name> myTag </name>
<tagclass> mylibrary.MyCustomTag </tagclass>
</tag>
</taglib>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 13
What is Tag Handler ?
• Is the Java class that is linked to a custom tag and 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
the same package.
• The most important interfaces are :
• Tag
• Iteration Tag
• Body Tag
• Class:
• SimpleTagSupport

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 14
The Tag Interface

• Contains the following methods


– doStartTag
– doEndTag
– getParent
– setParent
– setPageContext
– release
– NB:
• doStartTag return integers which could be SKIP_BODY,
EVAL_BODY_INCLUDE.
• doEndTag return integers which could be SKIP_PAGE,
and EVAL_PAGE

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 15
Example
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class BasicTagHandler implements Tag {
public void setParent(Tag t) {
}
public void setPageContext(PageContext p) {
}
public void release() {
}
public Tag getParent() {
return null;
}
public int doStartTag() {
return EVAL_BODY_INCLUDE;
}
public int doEndTag() {
return EVAL_PAGE;
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 16
The Tag Handler Life Cycle

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 17
The Tag Handler Life Cycle (cont’d)

1. The JSP container obtains an instance of the tag


handler from the pool or creates a new one. It then
calls the setPageContext, passing a PageContext
object representing the JSP page where the custom tag
is found.

2. The JSP container then calls the setParent method.


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 18
The Tag Handler Life Cycle (cont’d)

3.The JSP container then sets all the attributes in the


custom tag, if 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 of the return value of the doStartTag
method, the JSP container next calls the doEndTag
method.
6. The release method is the last method that the JSP
container calls.
7. The JSP container returns the instance of the tag
handler to a pool for future use.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 19
Using Custom tag in a JSP page

• you first need to use a taglib directive in your page.


<%@ taglib uri="tagLibraryURI" prefix="tagPrefix"
%>
• The uri attribute specifies an absolute or relative URI
that uniquely identifies the tag library descriptor
associated with this prefix
• Next to use it :
– <prefix:tagName/>
– <prefix:tagName>body</prefix:tagName>
– <m:myTag number="12" power="13"/>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 20
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 is preferable but not obligatory
• Example:
• <taglib>
– <taglib-uri> /myTld</taglib-uri>
– <taglib-location>/WEB-INF/taglib.tld </taglib-location>
</taglib>
– <%@ taglib uri="/myTld" prefix="easy"%>
– <easy:myTag/>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 21
Complete Example

• The tag handler will take the form:


public class DoublerTag implements SimpleTagSupport {

private int number;


public void setNumber(int number) {
this.number = number;
}

public void doTag() throws JspException {

JspWriter out = pageContext.getOut();


out.println("Double of " + number + " is " + (2 * number));

public void setNumber(int number) {


this.number = number;
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 22
Complete Example (cont’d)
• 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‖ "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
<tlibversion>1.0</tlibversion>
<shortname>Mytags</shortname>
<tag>
<name>myTag</name>
<tagclass>mylibrary.DoublerTag</tagclass>
<attribute>
<name>number</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>int</type>
</attribute>
</tag>
</taglib>
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 23
Complete Example (cont’d)

• The jsp page should include:

<%@ taglib uri="/WEB-INF/myTLD.tld― prefix=―JETS"%>

<JETS:myTag number="12"/>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 24
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 25
Assignment

• Create your own custom tag , and use in


in your jsp

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 26
Chapter 2

JSTL

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 27
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 28
What is JSTL ?

• It stands for ―JSP Standard


Tag Library‖
• What do we need to run
JSTL ?

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 29
The relation between JSP and JSTL

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 30
How to introduce those packages in your
code?

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 31
How does JSTL fix JSP problems?

• JSTL tags are XML, they cleanly and uniformly blend


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, because
they do not require any knowledge of programming or
Java.

• 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 32
JSTL main packages

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 33
JSTL main packages (Cont’d)

• The core library includes tags for the following uses:


– Accessing and modifying data in memory
– Making decisions in your pages
– Looping over data
• The XML library includes tags for the following purposes:
– 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 34
Core Package

• It depends mainly on Expression Language

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 35
Expression Language

• How Expression Language looks like ?


• It starts with ${ and ends with }
• Example :
– ${ 1+2}
• NB: Expression Language can be understood
inside JSTL Tags and JSP tags as well.
• Types of data read by EL?
• Scoped Variables
• Request Parameters

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 36
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 } page….request….session…..application
– ${user.phone} object
– ${header["User-Agent"]}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 37
Expression Language (cont’d)

• The default of scopes: Page-request-session then finally


application
• To be able to specify your variable scope :
– ${pageScope.username}
– ${requestScope.username}
– ${sessionScope.username}
– ${applicationScope.username}
• Example:
– ${sessionScope.shopping-Cart[0]}
– ${sessionScope.shoppingCart[1]}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 38
How to read request parameters?

• Simply by :
– ${param.name}
– ${paramValues.name}
• Example
<p>Wow, I know a lot about you...</p>
<p>Your name is ${param.username}/>.</p>
<p>Your password is ${param.pw}/>.</p>
<p>You are ${param.gender}/>.</p>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 39
Accessing other data with EL

• Implicit Objects supported by JSTL


– cookie: JSTL doesn’t give you a way to set cookies
(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 40
Page Context elements

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 41
Page Context elements (cont’d)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 42
Mathematical operators supported by EL

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 43
Comparisons supported by EL

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 44
Comparisons supported by EL (cont’d)

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


• Example of invalid statments:
– ${ ${user.weight} gt ${user.IQ} }
– ${user.weight} gt ${user.IQ}
• Only we can say :
– ${user.weight gt 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 45
To check if a certain parameter exists?

• Use the keyword : empty…. Return true or false


• Example:
• ${empty param.choice}
• ${empty sessionScope.userName}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 46
Core Package (cont.)

• Now back to core package.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 47
<c:out>

• Used for printing results of expressions


• Example:
– <c:out value="Hi, there!"/>
– <c:out value="${username}" default="Nobody"/>
– <c:out value="${username}">
Nothing
</c:out>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 48
<c:set>
• Used mainly to create scoped variables
• Example:
– <c:set var="four" value="${3 + 1}"/>
– <c:set var="four" scope="session" value="${3 +
1}"/>
– <c:set var="eight">
<c:out value="${4 * 2}"/>
</c:set>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 49
<c:remove >

• Used to delete data


• Example:
– <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 50
Controlling flow with conditions
<c:if>

• The <c:if> tag evaluates its test attribute, and if this


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

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 51
<c:if> (cont’d)

• You can use <c:if> tags anywhere in your page—even


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

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 52
Nested <c:if> tags

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

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 53
Complex conditional tags

• Mutually exclusive conditions with


<c:choose>,<c:when>, and <c:otherwise> …….
similar to switch statements
• The <c:choose> tag is simple: it takes no attributes
and serves only as a container
• for <c:when> and <c:otherwise> tags. Just as HTML’s
<td> tag makes no sense outside a <table>,
<c:when> and <c:otherwise> make no sense outside
a <c:choose>.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 54
Complex conditional tags (cont’d)

• 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.

• <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 55
Example

<c:choose>
<c:when test="${num==2}">
<li>Error 1 has occurred.</li>
</c:when>

<c:when test="${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>
</c:choose>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 56
Rules for using the complex conditional tags

1- <c:when> and <c:otherwise> tags cannot appear


outside a <c:choose> tag.
2- There’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
no more than one <c:otherwise>.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 57
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 58
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="${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 59
Advanced usage for iteration tags <c:forEach>

• you can determine information about the current item’s


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 60
Example

<c:forEach begin="1" end="5" var="current">


<c:out value="${current}"/>
</c:forEach>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 61
<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
variable instead of printing it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 62
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 application’s name using the
<c:import> tag’s context attribute.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 63
<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 64
Database Package

• We have to use :
– <%@ taglib prefix="sql"
uri="http://java.sun.com/jstl/sql" %>

• When to use database in JSP ? For presentation logic of the page as


background image

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 65
<sql:setDataSource>

• Setting up a database connection


– you can decide to expose a scoped variable that
represents the database

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 66
Example

 <sql:setDataSource
driver=―sun.jdbc.odbc.JdbcOdbcDriver"
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 67
<sql:query>

• Used to perform queries with

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 68
Example

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

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 69
<sql:query> (cont’d)

• Accessing metadata : u can get column names and 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>
<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 70
<sql:param>

• Example

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 71
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 72

You might also like