More Related Content
Similar to JSP Technology II
Similar to JSP Technology II (20)
More from People Strategists
More from People Strategists (7)
JSP Technology II
- 2. © People Strategists www.peoplestrategists.com Slide 2 of 45
In this session, you will learn to:
Work with JSTL tags
Identify custom tags
Implement EL
Objectives
- 5. © People Strategists www.peoplestrategists.com Slide 5 of 45
JSP was introduced with a vision of segregating the
UI-related code and the business logic-related code in Web applications.
However, the use of scriptlets in a JSP page does not fulfill the preceding
requirement.
In addition, the use of scriptlets leads to readability and maintenance
issues.
Therefore, JSTL was introduced to solve these problems.
JSTL is a tag library that consists of predefined tags to perform common
tasks in JSP pages, such as:
Iterating over a list of items.
Formatting the page output according to a specific condition.
Working with JSTL (Contd.)
- 6. © People Strategists www.peoplestrategists.com Slide 6 of 45
JSTL contains several types of tags.
JSTL tags are classified into the following categories according to their
functions:
Core tags
Formatting tags
Database tags
The core tags are used to perform the following tasks:
Implementing flow control
Iterating through a list
Implementing URL rewriting
Redirecting users to a new URL
Creating a URL with query parameters
Working with JSTL (Contd.)
- 7. © People Strategists www.peoplestrategists.com Slide 7 of 45
The core tags are divided into the following four groups, depending on
the function performed by the tags:
Variable support tags: Are used to access and manipulate the values of
variables in a JSP page. JSTL consists of two variable support tags, <set>
and <remove>.
Flow control tags: Are used to implement flow control in a JSP page. JSTL
consists of four flow control tags, <choose>, <forEach>, <forTokens>,
and <if>.
URL tags: Are used to perform tasks, such as rewriting URLs for session
management, including the contents of another page in a JSP page, and
redirecting a user to a JSP page. Some of the JSTL URL management tags
are, <import>, <redirect>, and <URL>.
Miscellaneous tags: Are used to output the value of a variable or property
or to implement exception handling. JSTL consists of two miscellaneous
tags, <out> and <catch>.
Identifying JSTL Core Tags
- 8. © People Strategists www.peoplestrategists.com Slide 8 of 45
The following table describes some of the JSTL core tags along with their
syntax:
Tag Description Syntax
<out>
Is used to display text or the value
of a variable
<c:out value=”Output Value”/>
<set>
Is used to assign a value to a
variable or property
<c:set var=”varName”
value=”value”
[scope=”{page|request|session|app
lication}”]/>
<if> Is used to evaluate a condition
<c:if test=”expression”
var=”varName”
[scope=”{page|request|session|app
lication}”] >
body </c:if>
<choose>
Is used to evaluate a condition. It
is similar to the switch…case
construct in Java
<c:choose>
When conditions
</c:choose>
<when>
Is the child tag of the <choose>
tag. It is similar to the case
statement of a switch…case
construct
<c:choose>
<c:when test condition>
</c:when>
</c:choose>
Identifying JSTL Core Tags (Contd.)
- 9. © People Strategists www.peoplestrategists.com Slide 9 of 45
Tag Description Syntax
<otherwise>
Is the child tag of the
<choose> tag. It is similar
to the default clause of the
switch…case construct
<c:otherwise>
Message text
</c:otherwise>
<import>
Is used to specify the
names of the files to be
inserted during the
compilation of the JSP
page
<c:import url="URL of the file
to be imported"/>
<forEach>
Is used to iterate over a
collection of objects
<c:forEach items=”collection”
[var=”varName”]
[varStatus=”varStatusName”]
[begin=”begin”] [end=”end”]
[step=”step”]>
body content
</c:forEach>
<url>
Is used to perform URL
rewriting
<c:url value='URL'/>
<redirect>
Is used to redirect a user to
a specific URL
<c:redirect url="URL to which
the user should be redirected/>
Identifying JSTL Core Tags (Contd.)
- 10. © People Strategists www.peoplestrategists.com Slide 10 of 45
To use JSTL core tags, you need to add a taglib directive in the desired JSP
page, as shown in the following code snippet:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
The following code snippet depicts the use of, <out>, the core tag in a
JSP page:
<%@taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Core Tags</title>
</head>
<body>
<c:out value="Hello there ! "/>
</body>
</html>
Identifying JSTL Core Tags (Contd.)
- 11. © People Strategists www.peoplestrategists.com Slide 11 of 45
The following code snippet depicts how to retrieve input variables in a
requested JSP page using JSTL:
<%@taglib
uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<html>
<body bgcolor="lightblue">
<form method=post action="jstldemo1.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>
jstldemo1.jsp
Identifying JSTL Core Tags (Contd.)
- 12. © People Strategists www.peoplestrategists.com Slide 12 of 45
The following code snippet depicts how to evaluate conditions using the
<if> tag in JSTL:
<%@ page contentType="text/html" %>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body bgcolor="lightgray">
<form method=post action="CheckCondition.jsp">
<select name="combo1">
<option value="sam">sam
<option value="tom">tom
</select>
<input type=submit value="Press me">
</form>
<c:set var="s" value="${param.combo1}" />
<strong> <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> </strong>
</body>
</html>
CheckCondition.jsp
Identifying JSTL Core Tags (Contd.)
- 13. © People Strategists www.peoplestrategists.com Slide 13 of 45
Consider a scenario where you need to create a JSP page using JSTL. The
JSP page should be based on the following guideline:
Identify the day of week and display it on Web page.
Saturday and Sunday should be displayed as weekend.
By default weekend should be displayed on Web page.
The Web page should be displayed as shown in the following figure.
Activity: Using Conditional Construct in JSTL
The Expected Output
- 14. © People Strategists www.peoplestrategists.com Slide 14 of 45
The following code snippet depicts how to use the forEach loop in
JSTL:
Identifying JSTL Core Tags (Contd.)
<%@ page contentType="text/html" %>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body bgcolor=lightblue>
<% pageContext.setAttribute("colors", new String[]
{"red","green","blue","orange","black"} ); %>
<table border=1 bgcolor="cyan" width="50%">
<c:forEach var="n" items="${colors}" varStatus="a">
<tr align="center">
<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>
</body>
</html>
- 15. © People Strategists www.peoplestrategists.com Slide 15 of 45
The following code snippet depicts how to use the import tag in JSTL:
Identifying JSTL Core Tags (Contd.)
<html>
<body>
WELCOME
<br>
</body>
</html>
<%@ page contentType="text/html" %>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body bgcolor=lightblue>
<c:import url="welcome.html"/>
<c:out value="to our web-site!" />
</body>
</html>
Welcome.html ImportDemo.jsp
- 16. © People Strategists www.peoplestrategists.com Slide 16 of 45
The following code snippet depicts how to link a Web page in JSTL:
The following code snippet depicts how to redirect a Web page in JSTL:
Identifying JSTL Core Tags (Contd.)
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<a href="<c:url value="welcome.html"/>">send </a>
</body>
</html>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:redirect url="welcome.html" />
</body>
</html>
- 17. © People Strategists www.peoplestrategists.com Slide 17 of 45
Formatting tags are used to format and display text, numbers, date, or
time in a specific format.
Some of the formatting tags include:
<formatNumber>
<parseNumber>
<formatDate>
<timeZone>
<setLocale>
Identifying JSTL Formatting Tags
- 18. © People Strategists www.peoplestrategists.com Slide 18 of 45
The following code snippet depicts the use of a formatting tag in a JSP
page:
Identifying JSTL Formatting Tags (Contd.)
<%@taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Formatting Tags</title>
</head>
<body>
<fmt:formatNumber value="123000.4509"
type="currency"/>
</body>
</html>
- 19. © People Strategists www.peoplestrategists.com Slide 19 of 45
Database tags are used to interact with relational databases, such as
Microsoft SQL Server and Oracle.
The following table describes some of the JSTL database tags along with
their syntax.
Identifying JSTL Database Tags
Tag Description Syntax
<setDataSource>
Is used to specify the name of the data
source that needs to be used in the
Web application
<sql:setDataSource var="data source name"
driver="driver name" url="data source URL"
user="database user id" password="database
password"/>
<query>
Is used to specify the query that needs
to be executed against the data source,
such as a SELECT or INSERT query
<sql:query dataSource="name of the data source"
var="name of the database">
//SQL statement to be executed
</sql:query>
<param>
Is used to specify the value for a SQL
command parameter
<sql:query dataSource="name of the data source"
var="name of the database">
<sql:param value="parameter value" />
</sql:query>
<transaction>
Is used to execute SQL statements as
part of a transaction
<sql:transaction dataSource="name of the data
source"> Body Content </sql:transaction>
- 20. © People Strategists www.peoplestrategists.com Slide 20 of 45
The following code snippet depicts the use of the database tag in a JSP
page:
Identifying JSTL Database Tags (Contd.)
<%@taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
<html>
<head>
<title>Core Tags</title>
</head>
<body>
<sql:setDataSource var="db"
driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://PC1:1433;databaseName=EmployeeDB;
user=sa;password=pass#1234"/>
<sql:query dataSource="${db}" var="result">
SELECT * from Emplyee;
</sql:query>
</body>
</html>
- 21. © People Strategists www.peoplestrategists.com Slide 21 of 45
Identifying Custom Tags
What is custom
tag?
- 23. © People Strategists www.peoplestrategists.com Slide 23 of 45
Custom tags can be classified into the following categories:
Empty tags: Refer to the custom tags that do not have any attribute or body
and are used to display simple information, such as the current date or a
message. The following code snippet shows an empty custom tag:
<td:welcome />
Tags with attributes: Refer to the custom tags that have attributes.
Attributes allow a developer to customize the behavior of custom tags. The
following code snippet shows a custom tag with an attribute named color:
<td: welcome color=”blue”></td:welcome>
Tags with a body: Refer to the custom tags that contain nested custom tags,
scripting elements, actions, HTML text, and JSP directives. The following
code snippet shows a custom tag that contains a JSP scripting element as its
body:
<td:welcome>
<%=today_date%>
</td:welcome>
Identifying Custom Tags (Contd.)
- 24. © People Strategists www.peoplestrategists.com Slide 24 of 45
The advantages of custom tags are:
They separate Java code from a JSP page.
They can be reused in different JSP pages.
They support standard Web application development job roles.
A custom tag consists of:
Tag handler: Consists of definitions of the classes and methods that define
the functionality of the tag.
Tag Library Descriptor (TLD) file: Is an XML file that describes the tag library.
Identifying Custom Tags (Contd.)
- 25. © People Strategists www.peoplestrategists.com Slide 25 of 45
A tag handler is a Java class that is used by the Web container to
evaluate a custom tag during the execution of the JSP page that
references the tag.
A tag handler class file derives its methods from the
javax.servlet.jsp.tagext package and implements the Tag,
SimpleTag, or BodyTag interfaces.
The Tag interface is implemented for tags with an empty body and the
SimpleTag and BodyTag interfaces are implemented for tags that use a
body.
Creating a Tag Handler
- 26. © People Strategists www.peoplestrategists.com Slide 26 of 45
The following table describes the classes of the
javax.servlet.jsp.tagext package.
Creating a Tag Handler (Contd.)
Class Description
BodyContent
Is a subclass of the JSPWriter class and represents the body content
of a tag
TagSupport Acts as a base class for tag handlers and implements empty tags
BodyTagSupport
Implements the BodyTag interface. This class is used to develop
custom tags with body
SimpleTagSupport
Is a base class for tag handlers that implement the SimpleTag
interface
TagData Represents the attributes and their values
TagInfo
Represents the information specified in the <tag></tag> element of
the TLD file. This class is used by the JSP engine while translating a JSP
page to a servlet
TagLibraryInfo
Represents the information of the TLD file, such as the tags it defines
and versioning information
TagVariableInfo Represents information about the variables of a custom tag
- 27. © People Strategists www.peoplestrategists.com Slide 27 of 45
To create a tag handler, you need to define the functionality of a custom
tag by using the following methods of the Tag interface:
Creating a Tag Handler (Contd.)
Method Description
doStartTag
Is invoked when the Web container encounters the start tag of a
custom tag.
doEndTag
Is invoked when the Web container encounters the end tag of a custom
tag.
release Is invoked to release the instance of the tag handler.
- 28. © People Strategists www.peoplestrategists.com Slide 28 of 45
The following table lists some of the methods that need to be
implemented according to the structure of the tag handler.
Creating a Tag Handler (Contd.)
Structure of the Tag Handler Methods to be Implemented
Simple tag with no body and no
attributes
doStartTag, doEndtag, and release
Tag with attributes doStartTag, doEndtag, and the
respective setAttribute and
getAttribute methods
Tags with body doStartTag, doEndTag, release,
doInitBody, doAfterBody
Tags that implement the
SimpleTag interface
doTag()
- 29. © People Strategists www.peoplestrategists.com Slide 29 of 45
The TLD file is an XML file that contains the tag library description.
The components of a TLD file can be categorized into two groups:
The first group consists of the elements that are part of the root tag of the
TLD or the taglib tag.
The second group, placed within the taglib tag, consists of the elements
that are a part of the tag element.
The taglib element is written as <taglib> and the tag element as
<tag>.
Identifying the TLD File
- 30. © People Strategists www.peoplestrategists.com Slide 30 of 45
The following table describes some of the sub tags of the <taglib>
element.
Identifying the TLD File (Contd.)
Sub tag Specify
<tlib-version>
The version of the tag library, such as
<tlib-version>1.0</tlib-version>
<jsp-version>
The version of JSP that the tag library depends on,
such as <jsp-version>1.2</jsp-version>
<short-name> The name for the tag library
<uri>
The universal resource identifier—an optional component that is a
unique id for the tag library
<tag> The details of a custom tag
- 31. © People Strategists www.peoplestrategists.com Slide 31 of 45
The following table describes some of the sub tags of the <tag>
element.
Identifying the TLD File (Contd.)
Sub tag Specify
<tag-class> The name of the tag handler of a custom tag
<body-content> Specifies the format of the body content of a custom tag
<name> The name of a custom tag
- 32. © People Strategists www.peoplestrategists.com Slide 32 of 45
The following code snippet shows a sample TLD file:
<taglib version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
jsptaglibrary_2_1.xsd">
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>tld1</short-name>
<uri>/WEB-INF/tlds/tld1</uri>
<tag>
<name>TestTag</name>
<tag-class>FirstServlet</tag-class>
</tag>
</taglib>
Identifying the TLD File (Contd.)
- 33. © People Strategists www.peoplestrategists.com Slide 33 of 45
Consider a scenario where you are assigned for a task that displays
current time on every Web page at the top left corner. For this, you need
to use custom tag so that you will create the custom tag once and can
use it number of times in future. The custom tag should display output as
shown in the following figure.
Activity: Implementing Custom Tags
The Expected Output
- 34. © People Strategists www.peoplestrategists.com Slide 34 of 45
Expression Language (EL):
is used extensively in JSTL tags.
can be used to create dynamic JSP pages.
EL is a scripting language that allows programmers to use simple
expressions to access and manipulate:
application data stored in JavaBeans components.
implicit objects.
Java classes.
collections elements.
scoped variables.
Implementing EL
- 35. © People Strategists www.peoplestrategists.com Slide 35 of 45
EL expressions can be used in the following ways:
As attribute values:
EL expressions can be used as attribute values in standard and custom tags.
The attribute values are replaced by the values generated after the evaluation of
EL expression.
The following code snippet shows the use of an EL expression as an attribute
value in the include tag:
<jsp:include page=”${location}”>
As text in a JSP page:
EL expressions can be used as text in a JSP page.
The text is displayed on the JSP page after the evaluation of an EL expression.
The following code will display a welcome message along with the value stored in
the variable, name:
<h1>Welcome ${name}</h1>
Implementing EL (Contd.)
- 36. © People Strategists www.peoplestrategists.com Slide 36 of 45
EL provides implicit objects that can be used to easily access all implicit
objects and scoped variables of JSP.
The following table describes some of the EL implicit objects.
Implementing EL (Contd.)
Implicit Object Description
pageContext Represents the JSP PageContext object for the current page
pageScope Maps the names and values of page-scoped variables or attributes
requestScope Maps the names and values of request-scoped variables or attributes
sessionScope Maps the names and values of session-scoped variables or attributes
applicationScope Maps the names and values of application-scoped variables or attributes
param Provides access to a request parameter value
paramValues Provides access to request parameter values as String arrays
initParam Maps a context initialization parameter name to a single value
cookie Maps a cookie name to a single cookie
headerValues Maps a request header name to an array of values
header Maps a request header name to a single value
- 37. © People Strategists www.peoplestrategists.com Slide 37 of 45
EL can also be used to access JavaBeans.
A JavaBean:
is a simple Java class that exposes internal fields as properties using the
corresponding getter and setter methods.
is a reusable and a self-contained software component that takes advantage
of all the security and platform-independent features of Java.
can be included in a JSP page to start processing user requests.
The following code snippet sets and retrieves the value of the
firstName property from a bean named customer:
<jsp:setProperty name="customer"
property="firstName" value="Sam" />
<h2>${customer.firstName}</h2>
Implementing EL (Contd.)
- 38. © People Strategists www.peoplestrategists.com Slide 38 of 45
EL supports the following types of operators:
Arithmetic operators
Relational operators
Logical operators
The following table describes the different arithmetic operators
supported by EL.
Implementing EL (Contd.)
Operator Description
+ It represents the addition operator.
- It represents the subtraction operator.
* It represents the multiplication operator.
/ and div It represents the division operator.
% and mod It represents the remainder operator.
- 39. © People Strategists www.peoplestrategists.com Slide 39 of 45
The following table describes the different relational operators
supported by EL.
Implementing EL (Contd.)
Operator Description
== and eq It represents the equality operator.
!= and ne It represents the not equal to operator.
< and lt It represents the less than operator.
> and gt It represents the greater than operator.
<= and le It represents the less than or equal to operator.
- 40. © People Strategists www.peoplestrategists.com Slide 40 of 45
The following table describes the different logical operators supported
by EL.
Implementing EL (Contd.)
Operator Description
&& and and It represents the AND operator.
|| and or It represents the OR operator.
! and not It represents the NOT operator.
- 41. © People Strategists www.peoplestrategists.com Slide 41 of 45
The following program illustrates how to sends the request to the
process.jsp which in turn prints the name of the user using EL.
Implementing EL (Contd.)
<html>
<body>
<form action="process.jsp">
Enter name:<input
type="text"
name="name"/><br/><br/>
<input type="submit"
value="go"/>
</form>
</body>
</html>
Default.jsp
<html>
<body>
Welcome, ${ param.name }
</body>
</html>
p1.jsp
- 42. © People Strategists www.peoplestrategists.com Slide 42 of 45
The following program illustrates how to store value in the session
object and retrieve it sessionScope object using EL.
Implementing EL (Contd.)
<html>
<body>
<h3>welcome to default
page</h3>
<%
session.setAttribute("user",
"peter");
%>
<a href="p1.jsp">Click here
</a> </body>
</html>
Default.jsp
<html>
<body>
Variable value is = ${
sessionScope.user }
</body>
</html>
p1.jsp
- 43. © People Strategists www.peoplestrategists.com Slide 43 of 45
Consider a scenario where you need to display the values entered in a
Web page and a context parameter value defined inside the web.xml file
inside the requested page. In addition, you are required to display
session details and set the background color of the requested Web page
using the pageContext object.
Activity: Implementing EL in JSP
The Expected Output
The Expected Output
- 44. © People Strategists www.peoplestrategists.com Slide 44 of 45
JSTL is a component of Java EE platform that contains a library of JSP
tags, which are required to perform common tasks in JSP pages.
JSTL tags are classified into the following categories according to their
functions:
Core tags
Formatting tags
Database tags
To use JSTL core tags, you need to add a taglib directive in the desired
JSP page.
A custom tag provides a mechanism that can be used by a Web
developer to encapsulate complex recurring code or tasks.
Custom tags can be classified into the following categories:
Empty tags
Tags with attributes
Tags with a body
Summary
- 45. © People Strategists www.peoplestrategists.com Slide 45 of 45
To create custom tags, you need to perform the following tasks:
Create a tag handler.
Create the TLD file.
A tag handler is a Java class that is used by the Web container to
evaluate a custom tag during the execution of the JSP page that
references the tag.
EL is a scripting language that allows programmers to use simple
expressions to access and manipulate the properties of a JSP page.
EL expressions can be used in the following ways:
As attribute values
As text in a JSP page
Summary (Contd.)