0% found this document useful (0 votes)
9 views63 pages

Javaserver Pages (JSP) : Faculty of Computing, Bahir Dar Institute of Technology, Bahir Dar University

The document provides an overview of JavaServer Pages (JSP), including its objectives, processing methods, constructs, predefined variables, and directives. It explains how JSP allows for the creation of dynamic web applications by embedding Java code within HTML, facilitating the separation of business logic from presentation logic. Additionally, it includes examples of JSP code and discusses the use of JavaBeans and error handling in JSP applications.

Uploaded by

denekew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views63 pages

Javaserver Pages (JSP) : Faculty of Computing, Bahir Dar Institute of Technology, Bahir Dar University

The document provides an overview of JavaServer Pages (JSP), including its objectives, processing methods, constructs, predefined variables, and directives. It explains how JSP allows for the creation of dynamic web applications by embedding Java code within HTML, facilitating the separation of business logic from presentation logic. Additionally, it includes examples of JSP code and discusses the use of JavaBeans and error handling in JSP applications.

Uploaded by

denekew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

JavaServer Pages (JSP)

By: Hagos Tesfahun


Faculty Of Computing,
Bahir Dar Institute of Technology,
Bahir Dar University

1
Objectives
• To create a simple JSP page .
• To explain how a JSP page is processed .
• To use JSP constructs to code JSP script.
• To use predefined variables and directives in JSP.
• To use JavaBeans components in JSP.
• To get and set JavaBeans properties in JSP.
• To associate JavaBeans properties with input parameters.
• To forward requests from one JSP page to another.
• To develop an application for browsing database tables using
JSP.

2
Introduction
• Java Server Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
• JSP enables you to write regular HTML script in the
normal way and embed Java code to produce dynamic
content.
• JSP can be easily managed because we can easily
separate our business logic with presentation logic.
• In Servlet technology, we mix our business logic with
the presentation logic.
• The JSP pages are easier to maintain than Servlet
because we can separate designing and development.
3
A Simple JSP
<!-- CurrentTime.jsp -->
<html>
<head>
<title>
Current Ttime
</title>
</head>
<body>
Current time is <% = new java.util.Date() %>
</body>
</html>

4
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

Web Browser Web Server /servlet/JSPFile.jsp

HTML Page returned


Process Generate Get JSP Generated
Servlet Response file Servlates

Servlet Get Servlet JSP


Engine Translator

NOTE: A JSP page is translated into a servlet when the page is requested for
the first time. It is not retranslated if the page is not modified.
5
JSP Constructs
There are three types of JSP scripting constructs you can use to insert
Java code into the resultant servlet. They are expressions, scriptlets,
and declarations.
expression A JSP expression is used to insert a Java
expression directly into the output. It has the
scriptlet
following form:
declaration <%= Java-expression %>

The expression is evaluated, converted into a


string, and sent to the output stream of the
servlet.

6
JSP Constructs
There are three types of JSP scripting constructs you can use to insert
Java code into the resultant servlet. They are expressions, scriptlets,
and declarations.
expression A JSP scriptlet enables you to insert a Java
statement into the servlet’s jspService method,
scriptlet
which is invoked by the service method. A JSP
declaration
scriptlet has the following form:

<% Java statement %>

7
JSP Constructs
There are three types of JSP scripting constructs you can use to insert
Java code into the resultant servlet. They are expressions, scriptlets,
and declarations.
expression A JSP declaration is for declaring methods or
fields into the servlet. It has the following form:
scriptlet

<%! Java method or field declaration %>


declaration

8
JSP Comment

HTML comments have the following form:


<!-- HTML Comment -->
If you don’t want the comment appear in the
resultant HTML file, use the following comment in
JSP:
<%-- JSP Comment --%>

9
<HTML>
<HEAD> Example: Computing Factorials
<TITLE>
Factorial
</TITLE>
</HEAD> JSP scriptlet
<BODY>

<% for (int i = 0; i <= 10; i++) { %>


Factorial of <%= i %> is
<%= computeFactorial(i) %> <br>
<% } %>
JSP expression
<%! private long computeFactorial(int n) {
if (n == 0)
return 1;
else
return n * computeFactorial(n - 1);
}
%>

</BODY> JSP declaration


</HTML>
10
CAUTION
• For JSP the loop body, even though it contains a
single statement, must be placed inside braces.
• It would be wrong to delete the opening brace ({) and
the closing brace (<% } %>) in the previous code.
• There is no semicolon at the end of a JSP
expression. For example, <%= i; %> is incorrect. But
there must be a semicolon for each Java statement in a
JSP scriptlet. For example, <% int i = 0; %>.
• JSP and Java elements are case sensitive, but HTML
is not.

11
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 client’s request, which is an
response
instance of HttpServletRequest. You can use it
out
session
to access request parameters, HTTP headers
application such as cookies, hostname, etc.
config
pagecontext
page

12
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
response
instance of HttpServletResponse. You can use it
out
session
to set response type and send output to the
application client.
config
pagecontext
page

13
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 character output stream, which
response
is an instance of PrintWriter obtained from
out
session
response.getWriter(). You can use it to send
application character content to the client.
config
pagecontext
page

14
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 HttpSession object associated
response
out
with the request, obtained from
session request.getSession().
application
config
pagecontext
page

15
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 ServletContext object for
response
out
storing persistent data for all clients. The
session difference between session and application is
application that session is tied to one client, but application
config is for all clients to share persistent data.
pagecontext
page

16
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 ServletConfig object for the
response
out
page.
session
application
config
pagecontext
page

17
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 PageContext object.
response
out
PageContext is a new class introduced in JSP to
session give a central point of access to many page
application attributes.
config
pagecontext
page

18
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
Page is an alternative to this.
response
out
session
application
config
pagecontext
page

19
<!-- ComputeLoan.html -->
<html> Example: Computing Loan
<head>
<title>ComputeLoan</title>
Write an HTML page that prompts
</head> the user to enter loan amount,
<body> annual interest rate, and number of
Compute Loan Payment years. Clicking the Compute Loan
Payment button invokes a JSP to
<form method="get" compute and display the monthly
and total loan payment.
action="http://localhost:8080/examples/jsp/ComputeLoan.jsp">
<p>Loan Amount
<input type="text" name="loanAmount"><br>
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>

20
<!-- 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>
21
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"
...
attributen="vlauen" %>
22
Three JSP Directives
Three possible directives are the following: page, include, and tablib.

page page lets you provide information for the page,


include such as importing classes and setting up content
tablib type. The page directive can appear anywhere in
the JSP file.

23
Three JSP Directives
Three possible directives are the following: page, include, and tablib.
page include lets you insert a file to the servlet when
include the page is translated to a servlet. The include
tablib directive must be placed where you want the file
to be inserted.

24
Three JSP Directives
Three possible directives are the following: page, include, and tablib.

page tablib lets you define custom tags.


include
tablib

25
Attributes for page Directives
import Specifies one or more packages to be imported
contentType
for this page. For example, the directive
session
buffer <%@ page import="java.util.*, java.text.*" %>
autoFlush imports java.util.* and java.text.*.
isThreadSafe
errorPage
isErrorPage

26
Attributes for page Directives
import Specifies the MIME(media type) type for the
contentType
resultant JSP page. By default, the content type
session
buffer is text/html for JSP. The default content type for
autoFlush servlets is text/plain.
isThreadSafe
errorPage
isErrorPage

27
Attributes for page Directives
import Specifies a boolean value to indicate whether the
contentType
page is part of the session. By default, session is
session
buffer true.
autoFlush
isThreadSafe
errorPage
isErrorPage

28
Attributes for page Directives
import Specifies the output stream buffer size. By
contentType
session
default, it is 8KB. For example, the directive
buffer <%@ page buffer="10KB" %> specifies that the
autoFlush output buffer size is 10KB. The directive
isThreadSafe <%@ page buffer="none" %> specifies that a
errorPage
isErrorPage
buffer is not used.

29
Attributes for page Directives
import Specifies a boolean value to indicate whether the
contentType
session
output buffer should be automatically flushed
buffer when it is full or whether an exception should be
autoFlush raised when the buffer overflows. By default,
isThreadSafe this attribute is true. In this case, the buffer
errorPage
isErrorPage
attribute cannot be none.

30
Attributes for page Directives
import Specifies a boolean value to indicate whether the
contentType
session
page can be accessed simultaneously without
buffer data corruption. By default, it is true. If it is set
autoFlush to false, the JSP page will be translated to a
isThreadSafe servlet that implements the SingleThreadModel
errorPage
isErrorPage
interface.

31
Attributes for page Directives
import errorPage specifies a JSP page that is processed
contentType
session
when an exception occurs in the current page.
buffer For example, the directive <%@ page
autoFlush errorPage="HandleError.jsp" %> specifies that
isThreadSafe
HandleError.jsp is processed when an exception
errorPage
isErrorPage
occurs.

isErrorPage specifies a boolean value to


indicate whether the page can be used as an error
page. By default, this attribute is false.

32
<!-- ComputeLoan.jsp -->
<html> Example: Computing Loan
<head>
Using the Loan Class
<title>ComputeLoan Using the Loan Class</title>
</head>
<body> Use the Loan class to simplify
<%@ page import = "bank.Loan" %> ComputingLoan.html. You can
<% double loanAmount = Double.parseDouble( create an object of Loan class and
use its monthlyPayment() and
request.getParameter("loanAmount"));
totalPayment() methods to compute
double annualInterestRate = Double.parseDouble(
the monthly payment and total
request.getParameter("annualInterestRate"));
payment.
int numberOfYears = Integer.parseInt(
request.getParameter("numberOfYears"));
Loan loan = new Loan(annualInterestRate, numberOfYears, Import a class. The class must be
loanAmount); placed in a package (e.g. package
%> bank).
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>

33
Example: Using Error Pages
This example prompts the user to enter an integer and displays the
factorial for the integer. If a non-integer value is entered by mistake,
an error page is displayed.

34
<!-- FactorialInput.html -->
<HTML>
<HEAD>
<TITLE>
FactorialInput
</TITLE>
</HEAD>
<BODY>
<FORM method="post"
action="http://localhost:8080/examples/jsp/ComputeFactorial.jsp">
Enter an integer <INPUT NAME="number"><BR><BR>
<INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Compute Factorial">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>

35
<!-- ComputeFactorial.jsp -->
<HTML>
<HEAD>
Error page
<TITLE>
ComputeFactorial
</TITLE>
</HEAD>
<BODY>
<%@ page import ="java.text.*" %>
<%@ page errorPage = "FactorialInputError.jsp" %>
<% NumberFormat format = NumberFormat.getNumberInstance();
int number = Integer.parseInt(request.getParameter("number")); %>
Factorial of <%= number %> is
<%= format.format(computeFactorial(number)) %> <p>
<%! private long computeFactorial(int n) {
if (n == 0)
return 1;
else
return n * computeFactorial(n - 1);
}
%>
</BODY>
</HTML>
36
<!-- FactorialInputError.jsp -->
<HTML>
<HEAD>
<TITLE>
FactorialInputError
</TITLE>
</HEAD>
<BODY> Indicate it is error
<%@ page isErrorPage = "true" %> page

<b>Error</b> -- Input is not an integer.

</BODY>
</HTML>

37
What is JavaBean?
JavaBeans are classes that encapsulate many objects into a single object (the bean).
It is a java class that should follow following conventions:
(1) It must be a public class;
(2) It must have a public no-arg constructor;
(3) It must implement the java.io.Serializable. (This requirement is not necessary in
JSP.)

class
Data members JavaBeans Component Minimum
Methods
Constructors requirement
public class
public no-arg constructor
serializable
may have accessor/mutator methods Optional
may have registration/deregistration methods requirement

38
Why JavaBeans?
The JavaBeans technology was developed to enable the
programmers to rapidly build applications by assembling
objects and test them during design time, thus making
reuse of the software more productive.
JavaBeans is a software component architecture that
extends the power of the Java language by enabling well-
formed objects to be manipulated visually at design time in
a pure Java builder tool, such as JBuilder and NetBeans.

39
JavaBeans Properties and Naming Patterns
• The get method is named
get<PropertyName>(),
which takes no parameters and returns an object of the type
identical to the property type.
• For a property of boolean type, the get method should be named
is<PropertyName>(),
which returns a boolean value.
• The set method should be named
set<PropertyName>(newValue),
which takes a single parameter identical to the property type and
returns void.

NOTE: A property may be read-only with a get method but no set


method, or write-only with a set method but no get method.
40
package studentProfile;
public class Student {
private String firstName;
private String mi;
private String lastName;
private String telephone;
private String street;
private String city;
private String state;
private String email;
private String zip;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMi() {
return this.mi;
}
public void setMi(String mi) {
this.mi = mi;
}

41
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}

42
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return this.zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}

43
Using JavaBeans in JSP
To create an instance for a JavaBeans component, use the
following syntax:
<jsp:useBean id="objectName" scope="scopeAttribute"
class="ClassName" />
This syntax is equivalent to
<% ClassName objectName = new ClassName() %>
except that the scope attribute specifies the scope of the
object.

44
Scope Attributes
application Specifies that the object is bound to the
session
application. The object can be shared by all
page
request sessions of the application.

45
Scope Attributes
application Specifies that the object is bound to the client’s
session
session. Recall that a client’s session is
page
request automatically created between a Web browser
and Web server. When a client from the same
browser accesses two servlets or two JSP pages
on the same server, the session is the same.

46
Scope Attributes
application The default scope, which specifies that the
session
object is bound to the page.
page
request

47
Scope Attributes
application Specifies that the object is bound to the client’s
session
page
request.
request

48
How Does JSP Find an Object
When <jsp:useBean id="objectName"
scope="scopeAttribute" class="ClassName" /> is
processed, the JSP engine first searches for the
object of the class with the same id and scope.
If found, the preexisting bean is used; otherwise, a
new bean is created.

49
Another Syntax for Creating a Bean
Here is another syntax for creating a bean using the
following statement:
<jsp:useBean id = "objectName" scope =
"scopeAttribute“ class = "ClassName" >
some statements
</jsp:useBean>
The statements are executed when the bean is created.
If the bean with the same id and className already exists,
the statements are not executed.

50
Example: Testing Bean Scope
This example creates a JavaBeans component named Count and uses
it to count the number of visits to a page.

51
<!-- TestBeanScope.jsp -->
<%@ page import = "chapter35.Count" %>
<jsp:useBean id="count" scope="application" class="chapter35.Count">
</jsp:useBean> package chapter27;

<HTML>
<HEAD> public class Count {

<TITLE>TestBeanScope</TITLE> private int count = 0;

</HEAD>
<BODY> /** Return count property */

<H3> public int getCount() {

Testing Bean Scope in JSP (Application) return count;

</H3> }

<% count.increaseCount(); %>


You are visitor number <%= count.getCount() %><br> /** Increase count */

From host: <%= request.getRemoteHost() %> public void increaseCount() {

and session: <%= session.getId() %> count++;

</BODY> }

</HTML> }
52
Getting and Setting Properties
By convention, A JavaBeans component provides
the get and set methods for reading and modifying
its private properties.
You can get the property in JSP using the following
syntax:
<jsp:getProperty name = "beanId“ property="sample" />

This is equivalent to
<%= beanId.getSample() %>

53
Getting and Setting Properties, cont.
You can set the property in JSP using the following
syntax:
<jsp:setProperty name="beanId“
property="sample“ value="test1" />
This is equivalent to
<% beanId.setSample("test1"); %>

54
Associating Properties with Input Parameters
Often properties are associated with input
parameters.
Suppose you want to get the value of the input
parameter named score and set it to the JavaBeans
property named score. You may write the following
code:
<% double score = Double.parseDouble(
request.getParameter("score")); %>
<jsp:setProperty name="beanId" property="score"
value= "<%= score %>" /> 55
Associating Properties with Input Parameters

This is cumbersome. JSP provides a convenient


syntax that can be used to simplify it as follows:
<jsp:setProperty name="beanId" property="score"
param="score" />

Instead of using the value attribute, you use the


param attribute to name an input parameter.
The value of this parameter is set to the property.

56
Associating All Properties
• Often the bean property and the parameter have
the same name.
• You can use the following convenient statement
to associate all the bean properties in beanId with
the parameters that match the property names.
<jsp:setProperty name="beanId" property="*" />

57
Example: Computing Loan Using JavaBeans
This Example demonstrates associating the bean properties
with the input parameters.
<!-- ComputeLoan.jsp -->
<html>
<head> Associating the bean
<title>ComputeLoan Using the Loan Class</title> properties with the
</head> input parameters.
<body>
<%@ page import = "chapter35.Loan" %>
<jsp:useBean id="loan" class="chapter35.Loan"></jsp:useBean>
<jsp:setProperty name="loan" property="*" />
Loan Amount: <%= loan.getLoanAmount() %><br>
Annual Interest Rate: <%= loan.getAnnualInterestRate() %><br>
Number of Years: <%= loan.getNumOfYears() %><br>
<b>Monthly Payment: <%= loan.monthlyPayment() %><br>
Total Payment: <%= loan.totalPayment() %><br></b>
</body>
</html>
58
Example: Computing Factorials Using JavaBeans
Create a JavaBeans component named FactorialBean and
use it to compute the factorial of an input number in a JSP
page named FactorialBean.jsp.

59
<!-- FactorialBean.jsp -->
<%@ page import = "chapter35.FactorialBean" %>
<jsp:useBean id="factorialBeanId" class="chapter35.FactorialBean"
>
Associating the bean
</jsp:useBean>
<jsp:setProperty name="factorialBeanId" property="*" />
properties with the
<HTML>
input parameters.
<HEAD>
<TITLE> FactorialBean </TITLE>
</HEAD>
<BODY>
<H3>Compute Factorial Using a Bean </H3>
<FORM method="post">
Enter new value: <INPUT NAME="number"><BR><BR>
<INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Compute Factorial">
<INPUT TYPE="RESET" VALUE="Reset">
<P>Factorial of
<jsp:getProperty name="factorialBeanId" property="number" /> is
Getting number
<%@ page import="java.text.*" %>
<% NumberFormat format = NumberFormat.getNumberInstance(); %>
<%= format.format(factorialBeanId.getFactorial()) %>
</FORM>
</BODY>
</HTML> 60
package chatper35;
public class FactorialBean {
private int number;

/** Return number property */


public int getNumber() {
return number;
}
/** Set number property */
public void setNumber(int newValue) {
number = newValue;
}
/** Obtain factorial */
public long getFactorial() {
long factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
return factorial;
}
}

61
Forwarding Requests from JavaServer Pages
Web applications developed using JSP generally consist of
many pages linked together.
JSP provides a forwarding tag in the following syntax that
can be used to forward a page to another page.
<jsp:forward page="destination" />

62
The End!!

63

You might also like