Understanding Java Servlets and Web Tech
Understanding Java Servlets and Web Tech
Servlet
1
Java Web Technology
⚫ There are different types of Web Technologies in Java,
of which the following are the most well-known
technologies.
1. Servlet
2. Java Server Page (JSP)
3. Java Server Face(JSF)
2
Objectives
• To understand the concept of servlets.
• To run servlets with Tomcat.
• To know the servlets API.
• To create simple servlets.
• To create and process HTML forms.
• To develop servlets to access databases.
• To use hidden fields, cookies, and HttpSession to
track sessions.
• To send images from servlets.
3
Introduction
⚫ What is a web application?
⚫ A web application is an application accessible from the web.
⚫ A web application is composed of web components like Servlet, JSP, JSF,
etc.
and other elements such as HTML, CSS, and JavaScript.
⚫ The web components typically execute in Web Server and respond to the
HTTP request.
⚫ Website
⚫ Website is a collection of related web pages that may contain text, images,
audio and video.
⚫ The first page of a website is called home page.
⚫ Each website has specific internet address (URL) that you need to enter in
your browser to access a website.
⚫ Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network.
⚫ A website is managed by its owner that can be an individual, company or an
organization.
⚫ A website can be of two types:
⚫ Static Website /Web Content
4 ⚫ Dynamic Website /Web Content
⚫ Static website is the basic type of website that is easy to create.
⚫ You don't need the knowledge of server side programming and database
design to create a static website.
⚫ Its web pages are coded in HTML.
⚫ Static web contents contain fixed number of pages and format of web
page is fixed which delivers information to the client.
⚫ Static web pages display the exact same information whenever anyone
visits it.
⚫ This works fine for static information that does not change regardless of
who requests it or when it is requested.
⚫ Static information is stored in files.
5
⚫ Dynamic website is a collection of dynamic web pages whose content changes dynamically.
⚫ It accesses content from a database or Content Management System (CMS).
⚫ Therefore, when you alter or update the content of the database, the content of the website is also altered or
updated.
⚫ Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.
⚫ Client side scripting generates content at the client computer on the basis of user input.
⚫ The web browser downloads the web page from the server and processes the code within the page to render
information to the user.
⚫ In server side scripting, the software runs on the server and processing is completed in the server then plain pages
are sent to the user. Dynamic Web pages are generated by Web servers.
⚫ Example:
⚫ Stock quotes are updated whenever a trade takes place.
⚫ Election vote counts are updated constantly on Election Day.
⚫ Weather reports are frequently updated.
⚫ The balance in a customer’s bank account is updated whenever a transaction takes place.
6
Static Website Dynamic Website
Prebuilt content is same every time the Content is generated quickly
page is loaded. and changes regularly.
It uses the HTML code for developing a It uses the server side languages such
website. as PHP, SERVLET, JSP, and
[Link] etc. for developing a website.
It sends exactly the same response for It may generate different HTML for
every request. each of the request.
The content is only changed when The page contains "server-side" code
someone publishes and updates the file which allows the server to generate the
(sends it to the web server). unique content when the page is loaded.
Flexibility is the main advantage of Content Management System (CMS) is
static website. the main advantage of dynamic website.
7
⚫ The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems.
⚫ It is the data communication protocol used to establish communication between client and
server.
⚫ HTTP is TCP/IP based communication protocol, which is used to deliver the data like
image files, query results, HTML files etc on the World Wide Web (WWW) with the
default port is HTTP 80.
⚫ It provides the standardized way for computers to communicate with each other.
8
The Basic Architecture of HTTP
⚫ HTTP is request/response protocol which is based on client/server based architecture.
⚫ In this protocol, web browser, search engines, etc. behave as HTTP clients and the
Web server like Servlet behaves as a server
⚫ The below diagram represents the basic architecture of web application and depicts
where HTTP stands:
9
Servlet
⚫ Servlet technology is used to create a web application (resides
at server side and generates a dynamic web page).
⚫ Servlet technology is robust and scalable because of
java language.
⚫ Servlets are Java programs that run on a Web server.
⚫ Servlets can be used to process client requests or
produce dynamic Web pages.
⚫ JSP, JSF, and Java Web services are based on servlets.
⚫ Before Servlet, CGI (Common Gateway Interface) scripting
language was common as a server-side
programming language.
10
⚫ CGI technology enables the web server to call an external program and pass HTTP request
information to the external program (CGI Program) to process the request.
⚫ For each request, it starts a new process.
⚫ CGI was proposed to generate dynamic Web content.
⚫ The CGI program processes the request and generates a response at runtime.
⚫ Disadvantages of CGI
⚫ There are many problems in CGI technology:
⚫ If the number of clients increases, it takes more time for sending the response.
⚫ For each request, it starts a process, and the web server is limited to start processes.
⚫ It uses platform dependent language e.g. C, C++, perl.
11
⚫ There are many advantages of Servlet over CGI.
⚫ The web container creates threads for handling the multiple requests to
the
Servlet.
⚫ Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads
are low.
⚫ The advantages of Servlet are as follows:
⚫ Better performance: because it creates a thread for each request, not process.
⚫ Portability: because it uses Java language.
⚫ Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
⚫ Secure: because it uses java language.
12
⚫ CGI provides a relatively simple approach for creating
dynamic Web applications that accept a user request,
process it on the server side, and return responses to the
Web browser.
⚫ But CGI is very slow when handling a large number of
requests simultaneously, because the Web server spawns
a process for executing each CGI program.
⚫ Each process has its own runtime environment that contains
and runs the CGI program.
⚫ It is not difficult to imagine what will happen if many CGI
programs were executed simultaneously.
⚫ System resource would be quickly exhausted,
potentially causing the server to crash.
13
⚫ Java are successful technology to solve the
servlets
performance problem of CGI programs .
⚫ Java servlets are Java programs that function like
CGI programs.
⚫ All servlets run inside a servlet container or a servlet server or
a servlet engine.
⚫ A servlet container is a single process that runs in a JVM.
⚫ The JVM creates a thread to handle each servlet.
⚫ All the threads share the same memory allocated to the JVM.
⚫ Servlets are much more efficient than CGI.
⚫ As Java programs, Servlets are object oriented, portable, and
platform independent.
14
⚫ The two most common HTTP requests or methods are GET
and POST.
⚫ The Web browser issues a request using a URL or an HTML
form to trigger the Web server to execute the servlet
program.
⚫ When issuing a request from an HTML form, either a
GET method or a POST method can be used.
⚫ If the GET method is used, the data in the form are appended
to the request string as if it were submitted using a URL.
⚫ If the POST method is used, the data in the form are packaged
as part of the request file.
⚫ The server program obtains the data by reading the file.
⚫ The POST method is more secure than the GET method.
15
⚫ The GET and POST methods both send requests to the Web server.
⚫ The POST method always triggers the execution of the
corresponding the servlet program.
⚫ The GET method may not cause the servlet program to be
executed, if the previous same request is cached in the Web
browser.
⚫ Web browsers often cache Web pages so that the same request can
be quickly responded to without contacting the Web server.
⚫ To ensure that a new Web page is always displayed, use the POST
method.
⚫ For example, use a POST method if the request will actually
update the database.
⚫ If your request is not time sensitive use the GET method to speed
up performance.
159
GET vs POST
GET POST
1) In case of Get request, only limited In case of Post request, large amount
amount of data can be sent because of data can be sent because data is
data is sent in header. sent in body.
5) Get request is more efficient and Post request is less efficient and
used more than Post. used less than get.
160
⚫ The servlet APIs are grouped into two packages: [Link]
and [Link] packages.
⚫ The [Link] and [Link] packages represent
interfaces and classes for servlet API.
⚫ The [Link] package contains many interfaces and
classes that are used by the servlet or web container. These
are not specific to any protocol.
⚫ The [Link] package contains interfaces and classes
that are responsible for http requests only.
⚫ Every servlet is a subclass of the HttpServlet class.
⚫ You need to override appropriate methods in the HttpServlet
class to implement the servlet.
18
The Servlet API
19
⚫ The [Link] interface defines the methods that all servlets
must implement. The methods are listed below:
20
⚫ The init, service, and destroy methods are known as life-cycle
methods and are called in the following sequence :
1. The init method is called when the servlet is first created and
is not called again as long as the servlet is not destroyed.
2. The service method is invoked each time the server receives a
request for the servlet. The server spawns/produces/generates
a new thread and invokes service.
21
The JVM uses the init, service, and destroy methods to control the
servlet.
165
⚫ The [Link] class defines a generic, protocol independent
servlet. This class is abstract class.
⚫ NOTE: GET and POST requests are often used, whereas DELETE,
PUT, OPTIONS, and TRACE are not.
25
HttpServlet inherits abstract class GenericServlet,
which implements interfaces Servlet
16
ServletConfig.
and
9
⚫ Every doXxx method in the HttpServlet class has a parameter
of the HttpServletRequest type, which is an object
that contains HTTP request information, including
parameter name and values, attributes, and an input
stream.
29
30
⚫ To run Java servlets, you need a servlet container.
⚫ Many servlet containers are available for free, but the
two popular ones are Tomcat and GlassFish.
⚫ Both Tomcat and GlassFish are bundled and integrated with
NetBeans 7 (Java EE version).
⚫ When you run a servlet from NetBeans, Tomcat or GlassFish
will be automatically started.
⚫ You can choose to use either of them, or any other application
server.
⚫ GlassFish has more features than Tomcat and it takes
more system resource.
31
⚫ To write a Java servlet, you define a class that extends
the
HttpServlet class.
⚫ The servlet container runs and controls the execution of the
servlet through the methods defined in the HttpServlet
class.
⚫ A servlet does not have a main method.
⚫ A servlet depends on the servlet engine to call the methods.
⚫ Every servlet has a structure like the one shown below:
32
import [Link].*;
import [Link].*;
import [Link].*;
public class MyServlet
extends HttpServlet {
public void init()
throws
ServletException {
...
}
public void
doGet(HttpServletReque
st request,
HttpServletResp
onse response)
throws
ServletException,
IOException {
...
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
...
}
33
public void destroy() {
⚫ The servlet engine controls the servlets using init, doGet,
doPost, destroy, and other methods.
⚫ By default, the doGet and doPost methods do nothing.
⚫ To handle a GET request, you need to override the doGet
method; to handle a POST request, you need to override
the doPost method.
⚫ The doGet method is invoked when the Web browser issues a
request using the GET method.
⚫ The doGet method has two parameters, request and response.
⚫ Request is for obtaining data from the Web browser and
response is for sending data back to the browser.
34
import [Link].*;
import [Link].*;
import [Link].*;
public class CurrentTime
extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<p>The current time is " +
new [Link]());
// Close stream
[Link]();
}
}
35
⚫ HTML forms enable you to submit data to the Web server in a
convenient form.
⚫ As shown in the following Figure, the form can contain text
fields, text area, check boxes, combo boxes, lists,
radio buttons, and buttons.
36
1. <form>
⚫ <form> ... </form> defines a form body.
⚫ The attributes for the <form> tag are action and method.
⚫ The action attribute specifies the server program to be executed
on the Web server when the form is submitted.
⚫ The method attribute is either get or post.
2. <label>
⚫ <label> ... </label> simply defines a label.
37
3. <input>
⚫ <input> defines an input field.
⚫ The attributes for this tag are type, name, value, checked, size, and
maxlength.
⚫ The type attribute specifies the input type.
⚫ Possible types are text for a one-line text field, radio for a
radio
button, and checkbox for a check box.
⚫ The name attribute gives a formal name for the attribute. This name
attribute is used by the servlet program to retrieve its associated value.
⚫ The names of the radio buttons in a group must be identical.
⚫ The value attribute specifies a default value for a text field and text
area.
⚫ The checked attribute indicates whether a radio button or a check box
is initially checked.
⚫ The size attribute specifies the size of a text field, and the maxlength
38 attribute specifies the maximum length of a text field.
4. <select>
⚫ <select> ... </select> defines a combo box or a list.
⚫ The attributes for this tag are name, size, and multiple.
⚫ The size attribute specifies the number of rows visible in the list.
⚫ The multiple attribute specifies that multiple values can
be
selected from a list.
⚫ Set size to 1 and do not use a multiple for a combo box.
39
5. <option>
⚫ <option> ... </option> defines a selection list within a
<select> ... </select> tag.
⚫ This tag may be used with the value attribute to specify a value
for the selected option (e.g., <option value = "CS">Computer
Science).
⚫ If no value is specified, the selected option is the value.
6. <textarea>
⚫ <textarea> ... </textarea> defines a text area.
⚫ The attributes are name, rows, and cols.
⚫ The rows and cols attributes specify the number of rows
and
columns in a text area.
40
<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h3>Student Registration Form</h3>
<form action = "GetParameters” method = "get">
<!-- Name text fields -->
<p><label>Last Name</label>
<input type = "text" name = "lastName" size = "20" />
<label>First Name</label>
<input type = "text" name = "firstName" size = "20" />
<label>MI</label>
<input type = "text" name = "mi" size = "1" /></p>
<!-- Gender radio buttons -->
<p><label>Gender:</label>
<input type = "radio" name = "gender" value = "M"
checked /> Male <input type = "radio" name = "gender" value
= "F" /> Female</p>
<!-- Major combo box -->
<p><label>Major</label>
<select name = "major" size = "1">
<option value = "CS">Computer Science</option>
<option value = "Math">Mathematics</option>
<option>English</option>
184
<option>Chinese</option>
</select>
<!-- Minor list -->
<label>Minor</label>
<select name = "minor" size = "2" multiple>
<option>Computer Science</option>
<option>Mathematics</option>
<option>English</option>
<option>Chinese</option>
</select></p>
<!-- Hobby check boxes -->
<p><label>Hobby: </label>
<input type = "checkbox" name = "tennis" /> Tennis
<input type = "checkbox" name = "golf" /> Golf
<input type = "checkbox" name = "pingPong" checked
/>Ping Pong
</p>
<!-- Remark text area -->
<p>Remarks: </p>
<p><textarea name = "remarks" rows = "3" cols = "56">
</textarea></p>
<!-- Submit and Reset buttons -->
<p><input type = "submit" value = "Submit" />
<input type = "reset" value = "Reset" /></p>
</form>
</body>
</html>
42
The End!!
43
Chapter 8
44
Java Server Pages (JSP)
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.
45
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.
⚫ The JSP pages are easier to maintain than Servlet because we can
separate designing and development.
46
A Simple
JSP
<!-- [Link] -->
<html>
<head>
<title>Current Ttime
</title>
</head>
<body>
Current time is <% = new [Link]() %>
</body>
</html>
47
How is a JSP Processed?
Web Server Host
URL Example
[Link]
Host Machine File System
NOTE: A JSP page is translated into a servlet when the page is requested for
1th91e first time. It is not retranslated if the page is not modified.
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.
A JSP expression is used to insert a Java
expression expression directly into the output. It has the following
form:
Scriptlet
<%= Java-expression %>
declaration
The expression is evaluated, converted into a
string, and sent to the output stream of the servlet.
49
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
50
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
51
JSP Comment
52
<HTML>
<HEAD> Example: Computing Factorials
<TITLE>
Factorial
</TITLE>
</HEAD> JSP scriptlet
<BODY>
<% } %>
JSP expression
<%! private long computeFactorial(int n) {
if (n == 0)
return 1;
else
return n * computeFactorial(n - 1);
}
%>
54
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
55
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
56
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
[Link](). You can use it to send
application character content to the client.
config
pagecontext
page
57
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 [Link]().
application
config
pagecontext
page
58
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
response
out
storing persistent data for all for
session clients.
difference between session and application is
application that session is tied to one client, butThe
application
config is for all clients to share persistent data.
pagecontext
page
59
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
response
out
the page.
session
applicati
on
config
pagecontext
page
60
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
applicati attributes.
on
config
pageco
ntext
page
61
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
applicati
on
config
pagecontext
page
62
<!-- [Link] -->
<html>
<head>
Example: Computing Loan
<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="[Link]
<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>
63
<!-- [Link] -->
<html>
<head>
<title>ComputeLoan</title> Predefined
</head>
variable
<body>
<% double loanAmount = [Link](
[Link]("loanAmount"));
double annualInterestRate = [Link](
[Link]("annualInterestRate"));
double numberOfYears = [Link](
[Link]("numberOfYears"));
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate /
(1 - 1 / [Link](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>
20
7 </html>
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 [Link] 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"
...
20
attributen="vlauen" %>
8
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.
66
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.
67
Three JSP Directives
Three possible directives are the following: page, include, and
tablib.
page tablib lets you define custom tags.
include
tablib
68
Attributes for page Directives
import Specifies one or more packages to be imported
contentType
session
for this page. For example, the directive
buffer <%@ page import="[Link].*, [Link].*" %>
autoFlush imports [Link].* and [Link].*.
isThreadSafe
errorPage
isErrorPage
69
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
70
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
71
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.
72
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.
73
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.
74
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="[Link]" %> specifies that
isThreadSafe
[Link] is processed when an exception
errorPage
isErrorPag
occurs.
e
isErrorPage specifies a boolean value to
indicate whether the page can be used as an error
page. By default, this attribute is false.
75
<!-- [Link] -->
<html>
<head>
Example: Computing Loan
<title>ComputeLoan Using the Loan Class</title> Using the Loan Class
</head>
<body> Use the Loan class to simplify
<%@ page import = "[Link]" %> [Link]. You can
<% double loanAmount = [Link]( create an object of Loan class and
use its monthlyPayment() and
[Link]("loanAmount"));
totalPayment() methods to compute
double annualInterestRate = [Link](
the monthly payment and total
[Link]("annualInterestRate")); payment.
int numberOfYears =
[Link]( [Link]("
numberOfYears")); Import a class. The class must be
Loan loan = new Loan(annualInterestRate, numberOfYears, placed in a package (e.g. package
loanAmount); bank).
%>
Loan Amount: <%= loanAmount %><br>
Annual Interest Rate: <%= annualInterestRate
%><br> Number of Years: <%= numberOfYears %><br>
<b>Monthly Payment: <%= [Link]()
%><br> Total Payment: <%= [Link]()
%><br></b>
76 </body>
</html>
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.
77
<!-- [Link] -->
<HTML>
<HEAD>
<TITLE>
FactorialInput
</TITLE>
</HEAD>
<BODY>
<FORM method="post"
action="[Link]
Enter an integer <INPUT NAME="number"><BR><BR>
<INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Compute Factorial">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
78
<!-- [Link] -->
<HTML>
<HEAD>
<TITLE>
Error page
ComputeFactorial
</TITLE>
</HEAD>
<BODY>
<%@ page import ="[Link].*" %>
<%@ page errorPage = "[Link]" %>
<% NumberFormat format = [Link]();
int number = [Link]([Link]("number")); %>
Factorial of <%= number %> is
<%= [Link](computeFactorial(number)) %> <p>
<%! private long computeFactorial(int n) {
if (n == 0)
return 1;
else
return
n *
computeFa
ctorial(n
- 1);
}
22%>
2
</BODY>
<!-- [Link] -->
<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>
80
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 [Link]. (This requirement is not necessary
in
JSP.)
class
Data JavaBeans Minimum
members
Methods
Component requirement
public class
Constructors public no-arg
constructor serializable
may have accessor/mutator
Optional
may have registration/deregistration
methods requirement
methods
81
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.
82
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.
86
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.
87
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.
88
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.
89
Scope Attributes
application The default scope, which specifies that the
session
object is bound to the page.
page
request
90
Scope Attributes
application Specifies that the object is bound to the client’s
session
page
request.
request
91
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.
92
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,
93
the statements are not executed.
Example: Testing Bean Scope
This example creates a JavaBeans component named Count and
uses it to count the number of visits to a page.
94
<!-- [Link] -->
<%@ page import = "[Link]" %>
<jsp:useBean id="count" scope="application" class="[Link]">
</jsp:useBean> package chapter27;
<HTML>
<HEAD> public class Count
</HEAD> 0;
</H3> }
</BODY> }
23
</HTML> }
8
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 = property="sample
"beanId“ " />
This is equivalent to
<%= [Link]()
96
%>
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
<%
[Link]("test1");
97 %>
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 =
[Link]( [Link]
arameter("score")); %>
<jsp:setProperty
24 name="beanId"
value= "<%= score
1
Associating Properties with Input Parameters
99
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="*" />
100
Example: Computing Loan Using JavaBeans
24
5
<!-- [Link] -->
<%@ page import = "[Link]" %>
<jsp:useBean id="factorialBeanId" class="[Link]"
>
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="[Link].*" %>
<% NumberFormat format = [Link](); %>
<%= [Link]([Link]()) %>
</FORM>
</BODY>
24
</HTML>
6
package chatper35;
public class FactorialBean
{ private int number;
105
The End!!
106
Chapter 9
Java Server Faces (JSF)
107
Java Server Faces (JSF)
Objectives
• To explain what JSF is.
• To create a JSF page using NetBeans.
• To create a JSF managed bean.
• To use JSF expressions in a facelet.
• To use JSF GUI components.
• To obtain and process input from a form.
• To track sessions in application, session, view, and
request scope.
• To validate input using the JSF validators.
• To bind database with facelets.
108
Introduction
⚫ Servlet is a primitive way to write server-side applications.
⚫ JSP provides a scripting capability and allows you to embed Java
code in XHTML.
⚫ It is easier to develop Web programs using JSP than servlets.
⚫ However, JSP has some problems.
⚫ It can be very confused, because it mixes Java code with HTML.
⚫ Using JSP to develop User Interface(UI) is tedious.
⚫ JavaServer Faces (JSF) comes to solve this problem.
⚫ JSF enables you to completely separate Java code from HTML.
⚫ You can quickly build web applications by assembling reusable UI
components in a page, connecting these components to Java
programs, and wiring client-generated events to server-side event
handlers.
⚫ The application developed using JSF is easy to debug and
252maintain.
XML Declaration
25
3
⚫ Facelets
⚫ A facelet is an XHTML page that mixes JSF tags with XHTML
tags.
⚫ XML Declaration
⚫ It is used to state that the document conforms to the XML version 1.0
and uses the UTF-8 encoding.
⚫ This declaration is optional, but it is a good practice to use it.
⚫ It must be the first item to appear in the document.
⚫ DOCTYPE
⚫ It specifies the version of XHTML used in the document.
⚫ This can be used by the Web browser to validate the syntax
of the document.
⚫ XML Comment
⚫ for documenting the contents in the file.
⚫ XML comment always begins with <!-- and end with -->.
254
⚫ Namespaces
⚫ Namespaces are like Java packages.
⚫ Java packages are used to organize classes and to avoid naming
conflict.
⚫ XHMTL namespaces are used to organize tags and
resolve naming conflict.
⚫ Each xmlns attribute has a name and a value separated
by an equal sign (=).
⚫ Example:
⚫ xmlns = [Link] specifies that any unqualified tag
names are defined in the default standard xhtml namespace.
⚫ xmlns:h = [Link] allows the tags defined in the JSF
tag library to be used in the document. These tags must have a
prefix h.
112
⚫ JSF are developed using the MVC
applications
architecture, which separates the application’s data
(model) from the graphical presentation (view).
⚫ The controller is the JSF framework that is responsible
for coordinating interactions between view and
the model.
⚫ In JSF, the facelets are the view for presenting data.
⚫ Data are obtained from Java objects.
⚫ Objects are defined using Java classes.
⚫ In JSF, the objects that are accessed from a facelet are
JavaBeans objects.
113
package jsfDemo;
import [Link];
import [Link];
import [Link];
@ManagedBean
@RequestScoped
public class TimeBean
{ public String getTime()
{
return new
Date().toString();
}
257}
Code Description
⚫ TimeBean is a with the @ManagedBean
JavaBeans
annotation, which indicates that the JSF framework will
create and manage the TimeBean objects used in the
application.
⚫ The @Override annotation tells the compiler that the
annotated method is required to override a method
in a superclass.
⚫ The @ManagedBean annotation tells the compiler to generate
the code to enable the bean to be used by JSF facelets.
⚫ The @RequestScope annotation specifies the scope of the
JavaBeans object is within a request.
⚫ You can also use @SessionScope or @ApplicationScope to
258 specify the scope for a session or for the entire application.
JSF Expressions
25
9
Example
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"[Link]
<html xmlns = "[Link]
xmlns:h = "[Link]
<h:head>
<title>Display Current Time</title>
<meta http-equiv="refresh" content ="60" />
</h:head>
<h:body>
The current time is "#{[Link]}"
</h:body>
26
0</html>
Code Description
⚫ The meta tag defined inside the h:head tag is used to tell
the browser to refresh every 60 seconds.
⚫ The JSF expression #{[Link]} is used to obtain the
current time.
⚫ timeBean is an object of the TimeBean class.
⚫ The object name can be changed in the @ManagedBean annotation
using the this
syntax: @ManagedBean(name = "anyObjectName“)
⚫ By default the object name is the class name with the first letter in
lowercase.
⚫ The JSF expression can either use property
the name or invoke the method to obtain the current
time.
#{[Link]} Or
118 #{[Link]()}
JSF GUI Components
119
JSF GUI Components
JSF Tag Description
h:form inserts an XHTML form into a page.
h:panelGroup similar to a Java flow layout container.
h:panelGrid similar to a Java grid layout container.
h:inputText displays a textbox for entering input.
h:outputText displays a textbox for displaying output.
h:commandButton It submits a form to the application.
h:inputTextArea displays a textarea for entering input.
h:commandLink It links to another page or location on a page.
h:inputHidden It allows a page author to include a
hidden variable in a page.
h:inputFile It allows a user to upload a file.
h:dataTable It represents a data wrapper.
h:inputSecret displays a textbox for entering password.
h3 :outputLabel displays a label.
2
6
JSF GUI Components
JSF Tag Description
h:outputLink displays a hypertext link.
h:selectOneMenu displays a combo box for selecting one item.
h:selectOneRadio displays a set of radio button.
h:selectBooleanCheckbox displays a checkbox.
h:selectOneListbox displays a list for selecting one item.
h:selectManyListbox displays a list for selecting multiple items.
f:selectItem specifies an item in an h:selectOneMenu,
h:selectOneRadio, or h:selectManyListbox.
h:outputFormat It displays a formatted message.
h:message displays a message for validating input.
h:messages It displays localized messages.
h:dataTable displays a data table.
h:column specifies a column in a data table.
264h:graphicImage displays an image.
Example: JSF GUI Components
This example displays a student registration
form by using some of JSF elements.
26
5
Example: JSF Code for the above
GUI
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"[Link]
<html xmlns = "[Link]
xmlns:h = "[Link]
xmlns:f="[Link]
<h:head>
<title>Student Registration Form</title>
</h:head>
<h:body>
<h:form>
<!-- Use h:graphicImage -->
<h3>Student Registration Form
<h:graphicImage name="[Link]"
library="image"/>
</h3>
<!-- Use h:panelGrid -->
<h:panelGrid columns="6"
style="color:green">
<h:outputLabel value="Last Name"/>
<h:inputText
id="lastNameInputText" />
<h:outputLabel value="First Name" />
26 <h:inputText
6 id="firstNameInputText" />
Example: JSF Code for the above
GUI
<!-- Use radio buttons -->
<h:panelGrid columns="2">
<h:outputLabel>Gender </h:outputLabel>
<h:selectOneRadio id="genderSelectOneRadio">
<f:selectItem itemValue="Male” itemLabel="Male"/>
<f:selectItem itemValue="Female”itemLabel="Female"/>
</h:selectOneRadio>
</h:panelGrid>
<!-- Use combo box and list -->
<h:panelGrid columns="4">
<h:outputLabel value="Major "/>
<h:selectOneMenu id="majorSelectOneMenu">
<f:selectItem itemValue="Computer Science"/>
<f:selectItem itemValue="Mathematics"/>
</h:selectOneMenu>
<h:outputLabel value="Minor "/>
<h:selectManyListbox id="minorSelectManyListbox">
<f:selectItem itemValue="Computer Science"/>
<f:selectItem itemValue="Mathematics"/>
<f:selectItem itemValue="English"/>
</h:selectManyListbox>
</h:panelGrid>
26
7
Example: JSF Code for the above
GUI
<!-- Use check boxes -->
<h:panelGrid columns="4">
<h:outputLabel value="Hobby: "/>
<h:selectManyCheckbox id="hobbySelectManyCheckbox">
<f:selectItem itemValue="Tennis"/>
<f:selectItem itemValue="Golf"/>
<f:selectItem itemValue="Ping Pong"/>
</h:selectManyCheckbox>
</h:panelGrid>
<!-- Use text area -->
<h:panelGrid columns="1">
<h:outputLabel>Remarks:</h:outputLabel>
<h:inputTextarea id="remarksInputTextarea"
style="width:400px; height:50px;" />
</h:panelGrid>
<!-- Use command button -->
<h:commandButton value="Register" />
</h:form>
</h:body>
</html>
26
8
Session Tracking
26
9
⚫ JSF provides several convenient and powerful ways for
input validation.
⚫ You can use the standard validator tags in the JSF Core
Tag Library or create custom validators.
⚫ The following Table lists some JSF input validator tags.
JSF Tag Description
f:validateLength validates the length of the input.
f:validateDoubleRange validates whether numeric input falls within acceptable range of
double values.
f:validateLongRange validates whether numeric input falls within acceptable range of
long values.
f:validateRequired validates whether a field is not empty.
27
1
Example: [Link]
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "
[Link]
<html xmlns="[Link]
xmlns:h="[Link]
xmlns:f="[Link]
<h:head>
<title>Validate Form</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="Name:"/>
<h:inputText id="nameInputText" required="true"
requiredMessage="Name is required"
validatorMessage="Name must have 1 to 10
chars" value="#{[Link]}">
<f:validateLength minimum="1" maximum="10" />
</h:inputText>
27 <h:message for="nameInputText"
2 style="color:red"/>
Example: [Link] …
<h:inputText id="ssnInputText" required="true"
requiredMessage="SSN is required"
validatorMessage="Invalid SSN”
value="#{[Link]}">
<f:validateRegex pattern="[\d]{3}-[\d]{2}-[\d]
{4}"/>
</h:inputText>
<h:message for="ssnInputText"
style="color:red"/>
<h:outputLabel value="Age:" />
<h:inputText id="ageInputText" required="true"
requiredMessage="Age is required"
validatorMessage="Age must be betwen 16 and
120" value="#{[Link]}">
<f:validateLongRange minimum="16" maximum="120"/>
</h:inputText>
<h:message for="ageInputText" style="color:red"/>
<h:outputLabel value="Heihgt:" />
<h:inputText id="heightInputText" required="true"
requiredMessage="Heihgt is required“
27 value="#{[Link]}“>
validatorMessage="Heihgt must be betwen 3.5 and
3
Example: [Link] …
131
Example: [Link]
import [Link];
import [Link];
@ManagedBean
@RequestScoped
public class ValidateForm {
private String name, ssn, ageString, heightString;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
[Link] = ssn;
}
public String getAgeString() {
return ageString;
}
132
Example: [Link]
public void setAgeString(String ageString) {
[Link] = ageString;
}
public String getHeightString() {
return heightString;
}
public void
setHeightString(String
heightString) {
[Link] = heightString;
}
public String getResponse() {
if (name == null || ssn == null
|| ageString
== null || heightString ==
null) {
return "";
}
else {
return "You entered " + "
Name: " + name
} + " SSN: " + ssn + " Age: "
133 + ageString
+ " Heihgt: " +
The End!!
27
7