Chapter 4 - JSP
Chapter 4 - JSP
Programming
Chapter 4 – JSP
MARSHIMA MOHD ROSLI
COMPUTER SCIENCE
JSP
What is JSP?
Advantages of JSP
MVC – JSP?
6
What are the different types of JSP tags?
Advantages
Code -- Computation
HTML -- Presentation
Separation of Roles
◦ Developers
◦ Content Authors/Graphic Designers/Web
Masters
Model-View-Controller
JSP
Bean
Servlet
JSP Big Picture
GET /hello.jsp
Hello.jsp
<html>Hello!</html> HelloServlet.java
Server w/
JSP Container
HelloServlet.class
JSP Lifecycle
11
A JSP File
A Simple JSP
<!-- CurrentTime.jsp -->
<HTML>
<HEAD>
<TITLE>
CurrentTime
</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
13
How Is a JSP Processed?
Web Server Host
URL Example
http://www.server.com:8080/servlet/JSPFile
Host Machine File System
Send a request URL
14
Activity
Explain the difference between Servlet and JSP.
JSP Constructs
There are three types of scripting constructs you can use to insert Java code into
the result servlet. They are expressions, scriptlets, and declarations.
16
JSP Constructs
There are three types of scripting constructs you can use to insert Java code into
the resultant servlet. They are expressions, scriptlets, and declarations.
17
JSP Constructs
There are three types of scripting constructs you can use to insert Java code into
the resultant servlet. They are expressions, scriptlets, and declarations.
18
JSP Comment
19
<HTML>
<HEAD> Example 40.1 Computing
<TITLE> Factorials
Factorial
</TITLE> JSP scriptlet
</HEAD>
<BODY>
20
Activity
Give examples
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined
variables from the servlet environment that can be used with JSP expressions and
scriptlets. These variables are also known as JSP implicit objects.
response
Represents the client’s request, which is an
out instance of HttpServletRequest. You can use it
session to access request parameters, HTTP headers
application such as cookies, hostname, etc.
config
pagecontext
page
22
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined variables from
the servlet environment that can be used with JSP expressions and scriptlets. These
variables are also known as JSP implicit objects.
request
Represents the servlet’s response, which is an
out instance of HttpServletResponse. You can use
session it to set response type and send output to the
application client.
config
pagecontext
page
23
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined variables from
the servlet environment that can be used with JSP expressions and scriptlets. These
variables are also known as JSP implicit objects.
request
response Represents the character output stream, which
is an instance of PrintWriter obtained from
session response.getWriter(). You can use it to send
application character content to the client.
config
pagecontext
page
24
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined variables from
the servlet environment that can be used with JSP expressions and scriptlets. These
variables are also known as JSP implicit objects.
request
response Represents the HttpSession object associated
out with the request, obtained from
request.getSession().
application
config
pagecontext
page
25
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined variables from
the servlet environment that can be used with JSP expressions and scriptlets. These
variables are also known as JSP implicit objects.
request
response Represents the ServletContext object for
out storing persistent data for all clients. The
session difference between session and application is
that session is tied to one client, but
config
application is for all clients to share persistent
pagecontext
page
data.
26
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined
variables from the servlet environment that can be used with JSP expressions and
scriptlets. These variables are also known as JSP implicit objects.
request
response Represents the ServletConfig object for the
out page.
session
application
pagecontext
page
27
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined
variables from the servlet environment that can be used with JSP expressions and
scriptlets. These variables are also known as JSP implicit objects.
request
response Represents the PageContext object.
out PageContext is a new class introduced in JSP to
session give a central point of access to many page
application attributes.
config
page
28
JSP Predefined Variables
You can use variables in JSP. For convenience, JSP provides eight predefined
variables from the servlet environment that can be used with JSP expressions and
scriptlets. These variables are also known as JSP implicit objects.
request
response Page is an alternative to this.
out
session
application
config
pagecontext
29
<!-- ComputeLoan.html -->
<html> Example 40.2
<head> Computing Loan
<title>ComputeLoan</title>
Write an HTML page that prompts
</head>
<body>
the user to enter loan amount,
Compute Loan Payment
annual interest rate, and number
of years. Clicking the Compute
<form method="get" action="ComputeLoan.jsp"> Loan Payment button invokes a
<p>Loan Amount JSP to compute and display the
<input type="text" name="loanAmount"><br> monthly and total loan payment.
Annual Interest Rate
<input type="text" name="annualInterestRate"><br>
Number of Years <input type="text" name="numberOfYears"
size="3"></p>
<p><input type="submit" name="Submit" value="Compute Loan
Payment">
<input type="reset" value="Reset"></p>
</form>
</body>
</html>
30
<!-- ComputeLoan.jsp -->
<html>
<head>
<title>ComputeLoan</title>
Predefined
</head>
variable
<body>
<% double loanAmount = Double.parseDouble(
request.getParameter("loanAmount"));
double annualInterestRate = Double.parseDouble(
request.getParameter("annualInterestRate"));
double numberOfYears = Integer.parseInt(
request.getParameter("numberOfYears"));
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate /
(1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12; %>
Loan Amount: <%= loanAmount %><br>
Annual Interest Rate: <%= annualInterestRate %><br>
Number of Years: <%= numberOfYears %><br>
<b>Monthly Payment: <%= monthlyPayment %><br>
Total Payment: <%= totalPayment %><br></b>
</body>
</html>
31
JSP Directives
A JSP directive is a statement that gives the JSP engine information about the
JSP page. For example, if your JSP page uses a Java class from a package other
than the java.lang package, you have to use a directive to import this package.
The general syntax for a JSP directive is as follows:
<%@ directive attribute="value" %>, or
<%@ directive attribute1="value1"
attribute2="value2"
...
attribute="vlauen" %>
32
Three JSP Directives
Three possible directives are the following: page, include, and taglib.
33
Three JSP Directives
Three possible directives are the following: page, include, and taglib.
page
include lets you insert a file to the servlet when
the page is translated to a servlet. The include
taglib directive must be placed where you want the file
to be inserted.
34
Three JSP Directives
Three possible directives are the following: page, include, and taglib
35
<!-- ComputeLoan.jsp -->
<html> Example: Computing
<head>
Loan Using the Loan
<title>ComputeLoan Using the Loan Class</title>
</head>
Class
<body> Use the Loan class to simplify
<%@ page import = "chapter40.Loan" %> Example 40.2. You can create
<% double loanAmount = Double.parseDouble( an object of Loan class and use
request.getParameter("loanAmount")); its monthlyPayment() and
double annualInterestRate = Double.parseDouble( totalPayment() methods to
request.getParameter("annualInterestRate")); compute the monthly payment
int numberOfYears = Integer.parseInt( and total payment.
request.getParameter("numberOfYears"));
Loan loan = new Loan(annualInterestRate, numberOfYears, Import a class. The class must be
loanAmount); placed in a package (e.g. package
%> chapter40.
Loan Amount: <%= loanAmount %><br>
Annual Interest Rate: <%= annualInterestRate %><br>
Number of Years: <%= numberOfYears %><br>
<b>Monthly Payment: <%= loan.monthlyPayment() %><br>
Total Payment: <%= loan.totalPayment() %><br></b>
</body>
</html>
36
What is JSTL?
JSTL (JSP Standard Tag Libraries) is a collection of JSP
custom tags developed by Java Community Process,
www.jcp.org. The reference implementation is developed
by the Jakarta project, jakarta.apache.org.
37
JSTL Tags
<c:if test="${2>0}">
It's true that (2>0)!
</c:if>
<html>
<head>
<title>Count to 10 in JSP scriptlet</title>
</head>
<body>
<% for(int i=1;i<=10;i++)
{%>
<%=i%><br/>
<%
}
%>
</body>
</html>
41
COUNT TO TEN EXAMPLE USING JSTL:
The following code shows how the count to ten example would be written
using JSTL. As you can see, this code listing is much more constant, as only
tags are used. HTML and JSTL tags are mixed to produce the example.
<body>
<c:forEach var="i" begin="1" end="10" step="1">
<c:out value="${i}" />
<br />
</c:forEach>
</body>
</html>
42
COUNT TO TEN EXAMPLE USING
JSTL:
When you examine the preceding source code, you can
see that the JSP page consists entirely of tags.
43
THE JSTL TAG LIBRARIES
The JSTL tags can be classified, according to their functions,
into following JSTL tag library groups that can be used when
creating a JSP page:
◦ Core Tags
◦ Formatting tags
◦ SQL tags
◦ XML tags
◦ JSTL Functions
44
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is
the syntax to include JSTL Core library in your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Tag Description
<c:catch> Catches any Throwable that occurs in its body and optionally exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>
<c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'.
<c:import> Retrieves an absolute or relative URL and exposes its contents to either the page,
a String in 'var', or a Reader in 'varReader'.
<c:forEach > The basic iteration tag, accepting many different collection types and supporting
subsetting and other functionality .
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or format.
<fmt:parseNumber> Parses the string representation of a number, currency, or
percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:setBundle> Loads a resource bundle and stores it in the named scoped variable or
the bundle configuration variable.
<fmt:timeZone> Specifies the time zone for any time formatting or parsing actions
nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
46
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such
as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for
prototyping
<sql:query> Executes the SQL query defined in its body or
through the sql attribute.
<sql:update> Executes the SQL update defined in its body or
through the sql attribute.
<sql:param> Sets a parameter in an SQL statement to the
specified value.
<sql:dateParam> Sets a parameter in an SQL statement to the
specified java.util.Date value.
<sql:transaction > Provides nested database action elements with a
shared Connection, set up to execute all
statements as one transaction. 47
XML TAGS:
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML
documents. Following is the syntax to include JSTL XML library in your JSP:
The JSTL XML tag library has custom tags for interacting with XML data. This
includes parsing XML, transforming XML data, and flow control based on XPath
expressions.
Before you proceed with the examples, you would need to copy following two
XML and XPath related libraries into your <Tomcat Installation Directory>\lib:
48
Following is the list of XML JSTL Tags:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an
<x:parse>
attribute or in the tag body.
<x:set > Sets a variable to the value of an XPath expression.
Evaluates a test XPath expression and if it is true, it
<x:if > processes its body. If the test condition is false, the
body is ignored.
<x:forEach> To loop over nodes in an XML document.
Simple conditional tag that establishes a context for
<x:choose> mutually exclusive conditional operations, marked by
<when> and <otherwise>
Subtag of <choose> that includes its body if its
<x:when >
expression evalutes to 'true'
Header.jsp
Gets input to compute loan from user index.jsp Footer.jsp
if(type.equals("S")) { <head>
<title>Simple</title>
%>
</head>
<jsp:forward page="/simple.jsp"/>
<body style="font-family:verdana;font-size:10pt;">
<%
<%@ include file="header.html" %>
} else {
<p style="color=#FF0000"><b><%=
%> exception.getMessage() %></b></p>
<jsp:forward page="/compound.jsp"/> <jsp:include page="footer.jsp"/>
<% </body>
} </html>
header.jsp
%>
<h3>Loan Calculator</h3>
footer.jsp
<%= new java.util.Date() %>
Loan Calculator
simple.jsp
<%@ page errorPage="error.jsp" %> <html>
<%! <head>
56
Review JSP
Open kahoot..
Developing a View Component
Design a view component
Develop a simple HTTP servlet
Configure and deploy a servlet
Developing a controller
component