Java Lanjut

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 145

1

2
6
Web Applications:
Part 1

2007 Pearson Education, Inc. All rights reserved.


2

If any man will draw up his case, and put his


name at the foot of the first page, I will give him
an immediate reply. Where he compels me to turn
over the sheet, he must wait my leisure.
Lord Sandwich

Rule One: Our client is always right


Rule Two: If you think our client is wrong,
see Rule One.
Anonymous

2007 Pearson Education, Inc. All rights reserved.


3

A fair question should be


followed by a deed in silence.
Dante Alighieri

You will come here and get books


that will open your eyes, and your ears,
and your curiosity, and turn you
inside out or outside in.
Ralph Waldo Emerson

2007 Pearson Education, Inc. All rights reserved.


4

OBJECTIVES
In this chapter you will learn:
Web application development using Java
Technologies and Java Studio Creator 2.0.
To create JavaServer Pages with JavaServer
Faces components.
To create web applications consisting of multiple
pages.
To validate user input on a web page.
To maintain state information about a user with
session tracking and cookies.

2007 Pearson Education, Inc. All rights reserved.


5

26.1 Introduction
26.2 Simple HTTP Transactions
26.3 Multitier Application Architecture
26.4 Java Web Technologies
26.4.1 Servlets
26.4.2 JavaServer Pages
26.4.3 JavaServer Faces
26.4.4 Web Technologies in Java Studio Creator 2
26.5 Creating and Running a Simple Application in Java
Studio Creator 2
26.5.1 Examining a JSP File
26.5.2 Examining a Page Bean File
26.5.3 Event-Processing Life Cycle
26.5.4 Relationship Between the JSP and Page Bean
Files

2007 Pearson Education, Inc. All rights reserved.


6

26.5.5 Examining the XHTML Generated by a Java Web


Application
26.5.6 Building a Web Application in Java Studio
Creator 2
26.6 JSF Components
26.6.1 Text and Graphics Components
26.6.2 Validation Using Validator Components and
Custom Validators
26.7 Session Tracking
26.7.1 Cookies
26.7.2 Session Tracking with the SessionBean Object
26.8 Wrap-Up
26.9 Web Resources

2007 Pearson Education, Inc. All rights reserved.


7

26.1 Introduction
Web-based applications create web content for
web browser clients
AJAXprovides interactivity and responsiveness
users typically expect of desktop applications

1992-2007 Pearson Education, Inc. All rights reserved.


8

26.2 Simple HTTP Transactions


Hypertext Transfer Protocol (HTTP)
set of methods and headers that allow clients and servers to
interact and exchange information
Simple web page
Typically an XHTML document
Contains markup that describes to a web browser how to
display the document
Hypertext data (hyperlinks)
link to different pages or to other parts of the same page
when the user clicks the link

1992-2007 Pearson Education, Inc. All rights reserved.


9

26.2 Simple HTTP Transactions


URIs (Uniform Resource Identifiers)
Identify data on the Internet
Those that specify the locations of documents are called
URLs (Uniform Resource Locators)
Common URLs refer to
Files
Directories
Objects that perform complex tasks
URL directs a browser to the resource (hosted on
a web server) that the user wishes to access

1992-2007 Pearson Education, Inc. All rights reserved.


10

26.2 Simple HTTP Transactions


HTTP GET method indicates that the client
wishes to obtain a resource from the server
HTTP headers provide information about the
data sent to a client, such as the MIME type
Multipurpose Internet Mail Extensions (MIME)
Internet standard that specifies data formats so that
programs can interpret data correctly

1992-2007 Pearson Education, Inc. All rights reserved.


11

Fig. 26.1 | Client interacting with web server. Step 1: The GET request.

2007 Pearson Education, Inc. All rights reserved.


12

Fig. 26.2 | Client interacting with web server. Step 2: The HTTP response.

2007 Pearson Education, Inc. All rights reserved.


13

26.3 Multitier Application Architecture


Web-based applications are multitier (or n-tier) applications that
divide functionality into separate tiers that typically reside on
separate computers
Bottom tier
Also called the data tier or the information tier
Maintains the applications data
Typically stores data in a relational database management system
(RDBMS)
Middle tier
Implements business logic, controller logic and presentation logic
Acts as an intermediary between data in the information tier and the
applications clients
Controller logic processes client requests and retrieves data from the
database
Presentation logic processes data from the information tier and presents
the content to the client

1992-2007 Pearson Education, Inc. All rights reserved.


14

26.3 Multitier Application Architecture


Web applications typically present data to clients as XHTML
documents.
Business logic in the middle tier
enforces business rules
ensures that data is reliable before the server application updates the
database or presents the data to users
Business rules dictate
How clients can and cannot access application data
How applications process data
Top tier
Also called client tier
The applications user interface, which gathers input and displays
output
Users interact with the application through the user interface, typically
in a web browser.

1992-2007 Pearson Education, Inc. All rights reserved.


15

26.3 Multitier Application Architecture

In response to user actions


Client tier interacts with middle tier to make requests and
to retrieve data from information tier
Client tier then displays data retrieved for the user
Client tier never directly interacts with the information tier

1992-2007 Pearson Education, Inc. All rights reserved.


16

Fig. 26.3 | Three-tier architecture.

2007 Pearson Education, Inc. All rights reserved.


17

26.4 Java Web Technologies


Continually evolve to provide developers with
higher levels of abstraction and greater
separation of the applications tiers
Separation makes web applications more
maintainable and extensible
Java Studio Creator 2
Drag-and-drop web-application GUI development
Business logic placed in separate Java classes

1992-2007 Pearson Education, Inc. All rights reserved.


18

26.4.1 Servlets
Use the HTTP request-response model of
communication between client and server
Extend a servers functionality by allowing the
server to generate dynamic content
Servlet container executes and interacts with
servlets
Packages javax.servlet and
javax.servlet.http contain the servlet
classes and interfaces.

1992-2007 Pearson Education, Inc. All rights reserved.


19

26.4.1 Servlets
Servlet container
Receives HTTP requests from clients
Directs each request to the appropriate servlet
Servlet processes the request and returns response to the
clienttypically an XHTML or XML document
Servlets implement the Servlet interface of
package javax.servlet
Ensures that each servlet can execute in the framework
Declares methods used by the servlet container to manage
the servlets life cycle

1992-2007 Pearson Education, Inc. All rights reserved.


20

26.4.1 Servlets
Servlet life cycle
Begins when the servlet container loads it into memoryusually
in response to the first request for the servlet
init method
- Called only once by container during a servlets life-cycle to initialize
the servlet
service method
- Called once per request
- Receives the request
- Processes it
- Sends a response to the client
destroy method
- Called to release any resources held by the servlet when container
terminates servlet

1992-2007 Pearson Education, Inc. All rights reserved.


21

26.4.2 JavaServer Pages


Extension of servlet technology
Each JSP is translated by the JSP container into a
servlet
Help separate presentation from content
Help web application programmers create
dynamic content
By reusing predefined components
By interacting with components using server-side
scripting

1992-2007 Pearson Education, Inc. All rights reserved.


22

26.4.2 JavaServer Pages


JavaBeans and custom tag libraries encapsulate
complex, dynamic functionality
Custom tag libraries
Allow Java developers to hide code for database access and
other complex operations in custom tags
Enable web-page designers who are not familiar with Java
to enhance web pages with powerful dynamic content and
processing capabilities
The JSP classes and interfaces are located in
packages javax.servlet.jsp and
javax.servlet.jsp.tagext.

1992-2007 Pearson Education, Inc. All rights reserved.


23

26.4.2 JavaServer Pages


Four key components
Directives
Actions
Scripting elements
Tag libraries
Directives
Messages to the JSP container
Specify page settings
Include content from other resources
Specify custom tag libraries for use in JSPs
Actions
Encapsulate functionality in predefined tags
Often are performed based on the information sent to the server as part
of a particular client request
Can create Java objects for use in JSPs

1992-2007 Pearson Education, Inc. All rights reserved.


24

26.4.2 JavaServer Pages


Scripting elements
Insert Java code that interacts with components in a JSP to perform
request processing
Tag libraries
Enable programmers to create custom tags
Enable web-page designers to manipulate JSP content without prior
Java knowledge
JavaServer Pages Standard Tag Library (JSTL)
Provides many common web application tasks
Static content
XHTML or XML markup
Known as fixed-template data or fixed-template text
Literal text is translated to a String literal in the servlet
representation of the JSP

1992-2007 Pearson Education, Inc. All rights reserved.


25

26.4.2 JavaServer Pages


First request for a JSP
Container translates the JSP into a servlet
Servlet handles the current and future requests to the JSP
JSPs rely on the same request/response
mechanism as servlets to process requests from
and send responses to clients

1992-2007 Pearson Education, Inc. All rights reserved.


26

Performance Tip 26.1

Some JSP containers translate JSPs into


servlets at the JSPs deployment time
(i.e., when the application is placed on a
web server). This eliminates the translation
overhead for the first client that requests
each JSP, as the JSP will be translated
before it is ever requested by a client.

2007 Pearson Education, Inc. All rights reserved.


27

26.4.3 JavaServer Faces


Web application framework
Simplifies the design of an applications user interface
Further separates a web applications presentation
from its business logic
Framework
Simplifies application development by providing libraries
and sometimes software tools to help you organize and
build your applications

1992-2007 Pearson Education, Inc. All rights reserved.


28

26.4.3 JavaServer Faces


JSF custom tag libraries
Contain user interface components that simplify web-page
design
Includes a set of APIs for handling component events
You design the look-and-feel of a page with JSF
by adding custom tags to a JSP file and
manipulating their attributes
You define the pages behavior in a separate Java
source-code file.

1992-2007 Pearson Education, Inc. All rights reserved.


29

26.4.4 Web Technologies in Java Studio


Creator 2
Java Studio Creator 2 web applications
Consist of one or more JSPs built in the JavaServer Faces
framework
Each has the file-name extension .jsp and contains the web
pages GUI elements
Java Studio Creator 2 allows you to
Design pages visually by dragging and dropping JSF
components onto a page;
Customize a web page by editing its .jsp file manually
Every JSP file created in Java Studio Creator 2 represents
a web page and has a corresponding JavaBean class called
the page bean

1992-2007 Pearson Education, Inc. All rights reserved.


30

26.4.4 Web Technologies in Java Studio


Creator 2
JavaBean class must have
Default (or no-argument) constructor
get and set methods for all of its properties.
page bean
Defines properties for each of the pages elements
Event handlers
Page life-cycle methods
Other supporting code for the web application
Every web application built with Java Studio Creator 2
has a page bean, a RequestBean, a SessionBean and
an ApplicationBean

1992-2007 Pearson Education, Inc. All rights reserved.


31

26.4.4 Web Technologies in Java Studio


Creator 2
RequestBean
Request scope
Exists only for the duration of an HTTP request
SessionBean
Session scope
Exists throughout a users browsing session or until the session times out
Unique SessionBean object for each user
ApplicationBean
Application scope
Shared by all instances of an application
Exists as long as the application remains deployed
Application-wide data storage or processing
One instance exists, regardless of the number of open sessions

1992-2007 Pearson Education, Inc. All rights reserved.


32

26.5 Creating and Running a Simple


Application in Java Studio Creator 2
Static Text components display text that cannot
be edited by the user

1992-2007 Pearson Education, Inc. All rights reserved.


33
Outline

Time.jsp
Tag libraries available for
use in this web application (1 of 2 )

Configure head section of


web page

2007 Pearson Education,


Inc. All rights reserved.
34
Outline
Set up a Static
Text element
Time.jsp

(2 of 2 )

2007 Pearson Education,


Inc. All rights reserved.
35

26.5.1 Examining a JSP File


Java Studio Creator 2 generates a JSP file in response to
your interactions with the Visual Editor
All JSPs have a jsp:root element
version attribute indicates the version of JSP being used
One or more xmlns attributes. Each xmlns attribute
specifies a prefix and a URL for a tag library, allowing the
page to use tags specified in that library.
All JSPs generated by Java Studio Creator 2 include the
tag libraries for
JSF core components library
JSF HTML components library
JSP standard components library
JSP user interface components library

1992-2007 Pearson Education, Inc. All rights reserved.


36

26.5.1 Examining a JSP File


The jsp:directive.page element
contentType attribute
- specifies the MIME type and the character set the page uses
pageEncoding attribute
- specifies the character encoding used by the page source
These attributes help the client determine how to render the content
All pages containing JSF components are represented in a component
tree with the root JSF element f:view (of type UIViewRoot)
All JSF component elements are placed in this element
Many ui page elements have a binding attribute to bind their
values to properties in the web applications JavaBeans
JSF Expression Language is used to perform these bindings.

1992-2007 Pearson Education, Inc. All rights reserved.


37

26.5.1 Examining a JSP File


ui:head element
title attribute that specifies the pages title
ui:link element
can be used to specify the CSS stylesheet used by a page
ui:body element
defines the body of the page
ui:form element
defines a form in a page.
ui:staticText component
displays text that does not change

1992-2007 Pearson Education, Inc. All rights reserved.


38

26.5.1 Examining a JSP File


JSP elements are mapped to XHTML elements
for rendering in a browser
Can map to different XHTML elements, depending on the
client browser and the components property settings
ui:staticText component
Typically maps to an XHTML span element
A span element contains text that is displayed on a web
page and is used to control the formatting of the text
style attribute of ui:staticText represented as part
of the corresponding span elements style attribute

1992-2007 Pearson Education, Inc. All rights reserved.


39

Fig. 26.5 | Sample JSF component tree.

2007 Pearson Education, Inc. All rights reserved.


40

26.5.2 Examining a Page Bean File


Page bean classes
Inherit from class AbstractPageBean (package
com.sun.rave.web.ui.appbase
Provides page life-cycle methods
Package com.sun.rave.web.ui.component
includes classes for many basic JSF components
A ui:staticText component is a
StaticText object (package
com.sun.rave.web.ui.component).

1992-2007 Pearson Education, Inc. All rights reserved.


1 // Fig. 26.6: Time.java 41
2
3
// Page bean file that sets clockText to the time on the web server.
Outline
package webtime;
4
5 import com.sun.rave.web.ui.appbase.AbstractPageBean;
6 import com.sun.rave.web.ui.component.Body;
Time.java
7 import com.sun.rave.web.ui.component.Form;
8 import com.sun.rave.web.ui.component.Head;
9
(1 of 8 )
import com.sun.rave.web.ui.component.Html;
10 import com.sun.rave.web.ui.component.Link;
11 import com.sun.rave.web.ui.component.Page;
12 import javax.faces.FacesException;
13 import com.sun.rave.web.ui.component.StaticText;
14 import java.text.DateFormat;
15 import java.util.Date;
16
17 public class Time extends AbstractPageBean
18 {
19 private int __placeholder;
20
21 // auto-generated component initialization method.
22 private void _init() throws Exception
23 {
24 // empty body
25 } // end method _init
26

2007 Pearson Education,


Inc. All rights reserved.
42
Outline

Time.java

(2 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
43
Outline

Time.java

(3 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
44
Outline

Time.java

(4 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
45
Code that was
inserted by the
Outline
designer to create a
StaticText object
Time.java

(5 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
46
Outline

Time.java

(6 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
47
Outline

Time.java

(7 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
48
Outline
Programmatically
change the text in
Time.java
the StaticText
object (8 of 8 )

2007 Pearson Education,


Inc. All rights reserved.
49

26.5.3 Event-Processing Life Cycle


Java Studio Creator 2s application model
Places methods init, preprocess, prerender and destroy in
the page bean that tie into the JSF event-processing life cycle
These represent four major stagesinitialization, preprocessing,
prerendering and destruction
init method
Called by the JSP container the first time the page is requested
and on postbacks
Postback occurs when form data is submitted, and the page and
its contents are sent to the server to be processed
invokes its superclass version, then tries to call the method
_init, which handles component initialization tasks

1992-2007 Pearson Education, Inc. All rights reserved.


50

26.5.3 Event-Processing Life Cycle


preprocess method
Called after init, but only if the page is processing a
postback
prerender method
Called just before a page is rendered by the browser
Should be used to set component properties
destroy method
Called after the page has been rendered, but only if the
init method was called
Handles tasks such as freeing resources used to render the
page

1992-2007 Pearson Education, Inc. All rights reserved.


51

26.5.4 Relationship Between the JSP and


Page Bean Files
Page bean
has a property for every element that appears in the JSP
file

1992-2007 Pearson Education, Inc. All rights reserved.


52

26.5.5 Examining the XHTML Generated


by a Java Web Application
To create a new web application
File > New Project
Select Web in the Categories pane
Select JSF Web Application in the Projects pane
Click Next
Specify the project name and location
Click Finish to create the web application project
Single web page named Page1 created and opened by default in the
Visual Editor in Design mode when the project first loads
Design mode shows how your page renders in abrowser
The JSP file for this page, named Page1.jsp, can be viewed by
clicking the JSP button at the top of the Visual Editor, or
right clicking anywhere in the Visual Editor and selecting Edit JSP
Source.

1992-2007 Pearson Education, Inc. All rights reserved.


53

26.5.5 Examining the XHTML Generated


by a Java Web Application
Preview in Browser button at the top of the
Visual Editor window allows you to view your
pages in a browser without having to build and
run the application
The Refresh button redraws the page in the
Visual Editor
The Target Browser Size drop-down list allows
you to specify the optimal browser resolution for
viewing the page and allows you to see what the
page will look like in different screen resolutions

1992-2007 Pearson Education, Inc. All rights reserved.


54

26.5.5 Examining the XHTML Generated


by a Java Web Application
Projects window displays the hierarchy of all the
projects files
Web Pages node contains the JSP files and includes the
resources folder, which contains the projects CSS
stylesheet and any other files the pages may need to display
properly (e.g., images)
The Java source code, including the page bean file for each
web page and the application, session and request scope
beans, can be found under the Source Packages node
Page Navigation file
Defines rules for navigating the projects pages

1992-2007 Pearson Education, Inc. All rights reserved.


55

26.5.5 Examining the XHTML Generated


by a Java Web Application
Methods init, preprocess, prerender and destroy are
overridden in each page bean
Serve as placeholders for you to customize the behavior of your web
application
Rename the JSP and Java files in your project, so that their names are
relevant to your application
Right click the JSP file in the Projects Window
Select Rename to display the Rename dialog
Enter the new file name
If Preview All Changes is checked, the Refactoring Window will
appear at the bottom of the IDE when you click Next >
No changes will be made until you click Do Refactoring in the
Refactoring Window.
If you do not preview the changes, refactoring occurs when you click
Next > in the Rename dialog.

1992-2007 Pearson Education, Inc. All rights reserved.


56

26.5.5 Examining the XHTML Generated


by a Java Web Application
Refactoring
the process of modifying source code to improve its readability and
reusability without changing its behavior
Examples: renaming methods or variables, breaking long methods into
shorter ones
Java Studio Creator 2 has built-in refactoring tools that automate some
refactoring tasks
Title property specifies JSPs title
Components are rendered using absolute positioning
Java Studio Creator 2 is a WYSIWYG (What You See Is What You
Get) editor
Outline window displays the page bean and the request, session and
application scope beans
Clicking an item in the page beans component tree selects the item in
the Visual Editor

1992-2007 Pearson Education, Inc. All rights reserved.


57

26.5.5 Examining the XHTML Generated


by a Java Web Application
To build and run application
Select Build > Build Main Project
Select Run > Run Main Project
If changes are made to a project, the project must
be rebuilt before the changes will be reflected
when the application is viewed in a browser
F5
build an application, then run it in debug mode
<Ctrl> F5
Program executes without debugging enabled.

1992-2007 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0"?> 58
2
3
Outline
<!-- Fig. 26.7: Time.html -->
4 <!-- The XHTML response generated when the browser requests Time.jsp. -->
5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
6 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Time.html
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9
(1 of 2 )
<meta content = "no-cache" http-equiv = "Pragma" />
10 <meta content = "no-cache" http-equiv = "Cache-Control" />
11 <meta content = "no-store" http-equiv = "Cache-Control" />
12 <meta content = "max-age=0" http-equiv = "Cache-Control" />
13 <meta content = "1" http-equiv = "Expires" />
14 <title>Web Time: A Simple Example</title>
15 <script type = "text/javascript"
16 src = "/WebTime/theme/com/sun/rave/web/ui/defaulttheme/
17 javascript/formElements.js"></script>
18 <link rel = "stylesheet" type = "text/css" href = "/WebTime/theme/
19 com/sun/rave/web/ui/defaulttheme/css/css_master.css" />
20 <link rel = "stylesheet" type = "text/css" href = "/WebTime/theme/
21 com/sun/rave/web/ui/defaulttheme/css/css_ie55up.css" />
22 <script type = "text/javascript">
23 var sjwuic_ScrollCookie = new sjwuic_ScrollCookie(
24 '/Time.jsp', '/WebTime/faces/Time.jsp' );
25 </script>

2007 Pearson Education,


Inc. All rights reserved.
59
Outline

Time.html

(2 of code
HTML 2 ) that
was generated for a
StaticText
object

2007 Pearson Education,


Inc. All rights reserved.
60

Fig. 26.8 | Visual Editor window in Design mode.

2007 Pearson Education, Inc. All rights reserved.


61

Fig. 26.9 | Palette in Java Studio Creator 2.

2007 Pearson Education, Inc. All rights reserved.


62

Fig. 26.10 | Projects window for the WebTime project.

2007 Pearson Education, Inc. All rights reserved.


63

Fig. 26.11 | JSP file generated for Page1 by Java Studio Creator 2.

2007 Pearson Education, Inc. All rights reserved.


64

Fig. 26.12 | Page bean file for Page1.jsp generated by Java Studio Creator 2.

2007 Pearson Education, Inc. All rights reserved.


65

Fig. 26.13 | Time.jsp after inserting the first Static Text component.

2007 Pearson Education, Inc. All rights reserved.


66

Fig. 26.14 | Time.jsp after adding the second Static Text component.

2007 Pearson Education, Inc. All rights reserved.


67

Fig. 26.15 | Outline window in Java Studio Creator 2.

2007 Pearson Education, Inc. All rights reserved.


68

Error-Prevention Tip 26.1

If you have trouble building your project


due to errors in the Java Studio Creator-
generated XML files used for building, try
cleaning the project and building again.
You can do this by selecting Build > Clean
and Build Main Project or by pressing
<Alt> B.

2007 Pearson Education, Inc. All rights reserved.


69

26.6 JSF Components

1992-2007 Pearson Education, Inc. All rights reserved.


70

Fig. 26.16 | Commonly used JSF components.

2007 Pearson Education, Inc. All rights reserved.


71

26.6.1 Text and Graphics Components

Grid Panel component


Designer can specify number of columns the grid should contain
Drop components anywhere inside the panel
Theyll automatically be repositioned into evenly spaced columns
in the order in which they are dropped
When the number of components exceeds the number of
columns, the panel moves the additional components to a new
row
Image component
Inserts an image into a web page
Images must be placed in the projects resources folder
Use url property to specify the image to display

1992-2007 Pearson Education, Inc. All rights reserved.


72

26.6.1 Text and Graphics Components

Text Field
Used to obtain text input from the user
Components JSP tags are added to the JSP file in the
order they are added to the page.
Tabbing between components navigates the components
in the order in which the JSP tags occur in the JSP file
To specify navigation order
Drag components onto the page in appropriate order, or
Set each input fields Tab Index property; tab index 1 is the
first in the tab sequence

1992-2007 Pearson Education, Inc. All rights reserved.


73

26.6.1 Text and Graphics Components


Drop Down List
displays a list from which the user can make a selection
To configure, right click the drop-down list in Design mode and select
Configure Default Options
Hyperlink
Adds a link to a web page
url property specifies the linked resource
Radio Button Group
Provides a series of radio buttons
Edit options by right clicking the component and selecting Configure
Default Options
Button
Triggers an action when clicked
Typically maps to an input XHTML element with attribute type set
to submit.

1992-2007 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "UTF-8"?> 74
2
3
Outline
<!-- Fig. 26.17: WebComponents.jsp -->
4 <!-- Registration form that demonstrates JSF components. -->
5 <jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6 xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
WebComponents
7 "http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
.jsp
8 <jsp:directive.page contentType = "text/html; charset = UTF-8"
9 pageEncoding = "UTF-8"/>
10
(1 of 5 )
<f:view>
11 <ui:page binding = "#{WebComponents.page}" id = "page">
12 <ui:html binding = "#{WebComponents.html}" id = "html">
13 <ui:head binding = "#{WebComponents.head}" id = "head">
14 <ui:link binding = "#{WebComponents.link}" id = "link"
15 url = "/resources/stylesheet.css"/>
16 </ui:head>
17 <ui:body binding = "#{WebComponents.body}" id = "body"
18 style = "-rave-layout: grid">
19 <ui:form binding = "#{WebComponents.form}" id = "form">
20 <ui:staticText binding = "#{WebComponents.header}"
21 id = "header" style = "font-size: 18px; left: 24px;
22 top: 24px; position: absolute" text = "This is a
23 sample registration form."/>
24 <ui:staticText binding = "#{WebComponents.instructions}"
25 id = "instructions" style = "font-style: italic;
26 left: 24px; top: 72px; position: absolute" text =
27 "Please fill in all fields and click Register."/>

2007 Pearson Education,


Inc. All rights reserved.
Designer generated 75
Outline
code for Image

Designer generated
code for Grid
WebComponents
Panel
.jsp

Designer
(2 of 5 )generated
code for Text
Field

2007 Pearson Education,


Inc. All rights reserved.
76
Outline

Designer generated
WebComponents
code for Drop
.jsp
Down List
(3 of 5 )
Designer generated
code for
Hyperlink

2007 Pearson Education,


Inc. All rights reserved.
Designer generated 77
Outline
code for Radio
Button Group

Designer generated
WebComponents
code for Button
.jsp

(4 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
78
Outline

WebComponents
.jsp

(5 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
79

26.6.2 Validation Using Validator


Components and Custom Validators
Validation
Helps prevent processing errors due to incomplete or improperly
formatted user input.
Length Validator
Determines whether a field contains an acceptable number of
characters
Double Range Validators and Long Range Validators
Determine whether numeric input falls within acceptable ranges
Package javax.faces.validators contains the
validator classes

1992-2007 Pearson Education, Inc. All rights reserved.


80

26.6.2 Validation Using Validator


Components and Custom Validators
Label component
Describes another component
Can be associated with a user input field by setting its for
property
Message component
Displays an error message when validation fails
To associate a Label or Message component
with another component, hold the Ctrl and Shift
keys, then drag the Label or Message to the
appropriate component

1992-2007 Pearson Education, Inc. All rights reserved.


81

26.6.2 Validation Using Validator


Components and Custom Validators
Set the required property of a component to
ensure that the user enters data for it.
An input fields required property must be set
to true for validation to occur
In the Visual Editor the label for a required field
is automatically marked by a red asterisk.
If a user submits a form with a missing required
field, the default error message for that field will
be displayed in its associated ui:message
component

1992-2007 Pearson Education, Inc. All rights reserved.


82

26.6.2 Validation Using Validator


Components and Custom Validators
To edit a Double Range Validators or a
Long Range Validators properties
Click its node in the Outline window in Design mode
Set the maximum and minimum properties in the
Properties window
Can limit user input length using validation
Set a Text Fields maxLength property

1992-2007 Pearson Education, Inc. All rights reserved.


83

26.6.2 Validation Using Validator


Components and Custom Validators
To ensure properly formatted input
Can match input against a regular expression
No built in regular expression, but you can add
your own custom validator methods to the page
bean file
Add a custom validator method
Right click the appropriate input component
Select Edit Event Handler > validate to create a
validation method in the page bean file

1992-2007 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "UTF-8"?> 84
2
3
Outline
<!-- Fig. 26.18: Validation.jsp -->
4 <!-- JSP that demonstrates validation of user input. -->
5 <jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6 xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
Validation.jsp
7 "http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
8 <jsp:directive.page contentType = "text/html; charset = UTF-8"
9 pageEncoding = "UTF-8"/>
(1 of 6 )
10 <f:view>
11 <ui:page binding = "#{Validation.page}" id = "page">
12 <ui:html binding = "#{Validation.html}" id = "html">
13 <ui:head binding = "#{Validation.head}" id = "head"
14 title = "Validation">
15 <ui:link binding = "#{Validation.link}" id = "link"
16 url = "/resources/stylesheet.css"/>
17 </ui:head>
18 <ui:body binding = "#{Validation.body}" focus = "form1:nameTF"
19 id = "body" style = "-rave-layout: grid">
20 <ui:form binding = "#{Validation.form}" id = "form">
21 <ui:staticText binding = "#{Validation.header}" id =
22 "header" style = "font-size: 16px; height: 22px;
23 left: 24px; top: 24px; position: absolute; width:
24 456px" text = "Please fill out the following form."/>
25 <ui:staticText binding = "#{Validation.instructions}"
26 id = "instructions" style = "font-size: 14px;
27 font-style: italic; left: 24px; top: 48px; position:
28 absolute; width: 406px" text = "All fields are
29 required and must contain valid information."/>

2007 Pearson Education,


Inc. All rights reserved.
85
Outline
Specifies the
validator for the
Validation.jsp
name Text Field

Specifies the
(2 of 6 )
validator for the
email Text Field

Specifies the
validator for the
phone number
Text Field

2007 Pearson Education,


Inc. All rights reserved.
86
Outline

Validation.jsp

(3 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
87
Outline

Validation.jsp

(4 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
88
Outline

Validation.jsp

(5 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
89
Outline

Validation.jsp

(6 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
90

26.7 Session Tracking


Personalization
Makes it possible for e-businesses to communicate
effectively with their customers
Improves the users ability to locate desired products and
services
Privacy
Some consumers embrace the idea of tailored content
Others fear the possible adverse consequences if the
information they provide to e-businesses is released or
collected by tracking technologies

1992-2007 Pearson Education, Inc. All rights reserved.


91

26.7 Session Tracking


To provide personalized services, must be able to
recognize clients
HTTP is a stateless protocol
It does not support persistent connections that would enable
web servers to maintain state information regarding
particular clients
To help the server distinguish among clients, each
client must identify itself to the server
Tracking individual clients
Cookies
SessionBean object

1992-2007 Pearson Education, Inc. All rights reserved.


92

26.7 Session Tracking


Other tracking methods
"hidden" form elements
- A web form can write session-tracking data into a form
- When the user submits the form, all the form data, including
the "hidden" fields, is sent to the form handler on the web
server
URL rewriting
- Web server embeds session-tracking information directly in
the URLs of hyperlinks that the user clicks to send
subsequent requests

1992-2007 Pearson Education, Inc. All rights reserved.


93

26.7.1 Cookies
Cookie
A piece of data typically stored in a text file on the users
computer
Maintains information about the client during and between
browser sessions
When a user visits the website, the users computer might
receive a cookie
This cookie is then reactivated each time the user revisits
that site
HTTP-based interactions between a client and a server
Includes a header containing information either about the
request (when the communication is from the client to the
server) or about the response (when the communication is
from the server to the client)

1992-2007 Pearson Education, Inc. All rights reserved.


94

26.7.1 Cookies
In a request, the header includes
Request type
Any cookies that have been sent previously from the server to be
stored on the client machine
In a response, the header includes
Any cookies the server wants to store on the client computer
Other information, such as the MIME type of the response
Expiration date determines how long the cookie remains
on the clients computer
If not set, the web browser maintains the cookie for the browsing
sessions duration

1992-2007 Pearson Education, Inc. All rights reserved.


95

26.7.1 Cookies
Setting the action handler for a Hyperlink
enables you to respond to a click without
redirecting the user to another page
To add an action handler to a Hyperlink that
should also direct the user to another page
Add a rule to the Page Navigation file
Right click in the Visual Designer and select Page
Navigation, then drag the appropriate Hyperlink to
the destination page

1992-2007 Pearson Education, Inc. All rights reserved.


96

26.7.1 Cookies
A cookie object is an instance of class Cookie in package
javax.servlet.http
An HttpServletResponse (from package
javax.servlet.http) represents the response
This object can be accessed by invoking the method
getExternalContext on the page bean, then invoking
getResponse on the resulting object
An HttpServletRequest (from package
javax.servlet.http) represents the request
This object can be obtained by invoking method
getExternalContext on the page bean, then invoking getRequest
on the resulting object.
HttpServletRequest method getCookies returns an array of
the cookies previously written to the client.
Web server cannot access cookies created by servers in other domains

1992-2007 Pearson Education, Inc. All rights reserved.


97
Outline

Validation.java

(1 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
98
Outline

Validation.java

(2 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
99
Outline

Validation.java

(3 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
100
Outline

Validation.java

(4 of 5 )

Custom email
validation via
regular expression

2007 Pearson Education,


Inc. All rights reserved.
101
Custom phoneOutline
number validation
via regular
expression
Validation.java

(5 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
102

Portability Tip 26.1

Clients may disable cookies in their web


browsers for more privacy. When such
clients use web applications that depend on
cookies to maintain state information, the
applications will not execute correctly.

2007 Pearson Education, Inc. All rights reserved.


1 <?xml version = "1.0" encoding = "UTF-8"?> 103
2
3
Outline
<!-- Fig. 26.20: Options.jsp -->
4 <!-- JSP file that allows the user to select a programming language. -->
5 <jsp:root version = "1.2" xmlns:f = "http://java.sun.com/jsf/core"
6 xmlns:h = "http://java.sun.com/jsf/html" xmlns:jsp =
Options.jsp
7 "http://java.sun.com/JSP/Page" xmlns:ui = "http://www.sun.com/web/ui">
8 <jsp:directive.page contentType = "text/html; charset = UTF-8"
9
(1 of 4 )
pageEncoding = "UTF-8"/>
10 <f:view>
11 <ui:page binding = "#{Options.page}" id = "page">
12 <ui:html binding = "#{Options.html}" id = "html">
13 <ui:head binding = "#{Options.head}" id = "head" title =
14 "Options">
15 <ui:link binding = "#{Options.link}" id = "link"
16 url = "/resources/stylesheet.css"/>
17 </ui:head>
18 <ui:body binding = "#{Options.body}" id = "body"
19 style = "-rave-layout: grid">
20 <ui:form binding = "#{Options.form}" id = "form">
21 <ui:label binding = "#{Options.languageLabel}" for =
22 "languageList" id = "languageLabel" style =
23 "font-size: 16px; font-weight: bold; left: 24px; top:
24 24px; position: absolute" text = "Select a
25 programming language:"/>
26 <ui:radioButtonGroup binding = "#{Options.languageList}"
27 id = "languageList" items =
28 "#{Options.languageListOptions.options}" style =
29 "left: 24px; top: 48px; position: absolute"/>

2007 Pearson Education,


Inc. All rights reserved.
104
Outline

Options.jsp

(2 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
105
Outline

Options.jsp

(3 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
106
Outline

Options.jsp

(4 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
107

Fig. 26.21 | Editing the Page Navigation file.

2007 Pearson Education, Inc. All rights reserved.


108
Outline

Options.java

(1 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
109
Outline

Options.java

(2 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
110
Outline

Options.java

(3 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
111
Outline

Options.java

(4 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
112
Outline

Options.java

(5 of 6 )

Creates the
Cookie object

Gets the response


object and adds the
Cookie to the
response

2007 Pearson Education,


Inc. All rights reserved.
113
Outline

Options.java

(6 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
114

Software Engineering Observation 26.1

Java Studio Creator 2 can automatically


import any missing packages your Java file
needs. For example, after adding the
Properties object to Options.java, you
can right click in the Java editor window and
select Fix Imports to automatically import
java.util.Properties.

2007 Pearson Education, Inc. All rights reserved.


115
Outline

Recommendations .
jsp

(1 of 2 )

2007 Pearson Education,


Inc. All rights reserved.
30 <ui:hyperlink action = "case1" binding = 116
31
32
"#{Recommendations.optionsLink}" id = "optionsLink"
Outline
style = "left: 24px; top: 192px; position: absolute"
33 text = "Click here to choose another language."/>
34 </ui:form>
35 </ui:body>
Recommendations .
36 </ui:html>
jsp
37 </ui:page>
38 </f:view>
39 </jsp:root>
(2 of 2 )

2007 Pearson Education,


Inc. All rights reserved.
117
Outline

Recommendations .
java

(1 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
118
Outline

Recommendations .
java

(2 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
119
Outline

Recommendations .
java

(3 of 4 )

Obtains the
Cookie object(s)
from the request

2007 Pearson Education,


Inc. All rights reserved.
202 120
203
204
if ( cookies.length > 1 )
Outline
{
205 recommendations = new Option[ cookies.length - 1 ];
206 for ( int i = 0; i < cookies.length - 1; i++ )
207 {
Recommendations .
208 String language =
java
209 cookies[ i ].getName().replace( /, );
210 recommendations[ i ] = new Option( language + " How to "
211
(4 of 4 )
"Program. ISBN#: " + cookies[ i ].getValue() );
212 } // end for
213 } // end if
214
215 // otherwise store a message indicating no language was selected
216 else
217 {
218 recommendations = new Option[ 1 ];
219 recommendations[ 0 ] = new Option( "No recommendations. " +
220 "Please select a language." ) ;
221 } // end else
222
223 booksListBox.setItems( recommendations );
224 } // end method prerender
225
226 public void destroy()
227 {
228 // empty body
229 } // end method destroy
230 } // end class Recommendations

2007 Pearson Education,


Inc. All rights reserved.
121

Fig. 26.25 | javax.servlet.http.Cookie methods.

2007 Pearson Education, Inc. All rights reserved.


122

26.7.2 Session Tracking with the


SessionBean Object
Can perform session tracking with class SessionBean that is
provided in each web application created with Java Studio Creator 2
When a new client requests a web page in the project, a SessionBean
object is created.
The SessionBean can be accessed throughout a session by invoking
the method getSessionBean on the page bean
Can then use the SessionBean object to access stored session
properties
To store information in the SessionBean
Add properties to the SessionBean class
To add a property
- Right click the SessionBean node in the Outline window
- Select Add > Property to display the New Property Pattern dialog
- Configure the property and click OK to create it

1992-2007 Pearson Education, Inc. All rights reserved.


123
Outline

Options.jsp

(1 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
124
Outline

Options.jsp

(2 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
51 <ui:hyperlink binding = "#{Options.recommendationsLink}" 125
52
53
id = "recommendationsLink" rendered = "false" style =
Outline
"left: 24px; top: 168px; position: absolute" text =
54 "Click here to get book recommendations." url =
55 "/faces/Recommendations.jsp"/>
56 </ui:form>
Options.jsp
57 </ui:body>
58 </ui:html>
59 </ui:page>
(3 of 5 )
60 </f:view>
61 </jsp:root>

2007 Pearson Education,


Inc. All rights reserved.
126
Outline

Options.jsp

(4 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
127
Outline

Options.jsp

(5 of 5 )

2007 Pearson Education,


Inc. All rights reserved.
128

Fig. 26.27 | New Property dialog for adding a property to the SessionBean.

2007 Pearson Education, Inc. All rights reserved.


129

Fig. 26.28 | Bind to Data dialog.

2007 Pearson Education, Inc. All rights reserved.


130
Outline

SessionBean.java

(1 of 3 )

2007 Pearson Education,


Inc. All rights reserved.
131
Outline

SessionBean.java

(2 of 3 )

2007 Pearson Education,


Inc. All rights reserved.
132
Outline

SessionBean.java

(3 of 3 )

Manually coded
Properties
object

2007 Pearson Education,


Inc. All rights reserved.
1 // Fig. 26.30: Options.java 133
2
3
// Page bean that stores language selections in a SessionBean property.
Outline
package session;
4
5 import com.sun.rave.web.ui.appbase.AbstractPageBean;
6 import com.sun.rave.web.ui.component.Body;
Options.java
7 import com.sun.rave.web.ui.component.Form;
8 import com.sun.rave.web.ui.component.Head;
9 import com.sun.rave.web.ui.component.Html;
(1 of 6 )
10 import com.sun.rave.web.ui.component.Link;
11 import com.sun.rave.web.ui.component.Page;
12 import javax.faces.FacesException;
13 import com.sun.rave.web.ui.component.RadioButtonGroup;
14 import com.sun.rave.web.ui.component.Hyperlink;
15 import com.sun.rave.web.ui.component.Button;
16 import com.sun.rave.web.ui.component.Label;
17 import com.sun.rave.web.ui.component.StaticText;
18 import com.sun.rave.web.ui.model.SingleSelectOptionsList;
19 import java.util.Properties;
20 import javax.servlet.http.Cookie;
21 import javax.servlet.http.HttpServletRequest;
22 import javax.servlet.http.HttpSession;
23

2007 Pearson Education,


Inc. All rights reserved.
134
Outline

Options.java

(2 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
135
Outline

Options.java

(3 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
136
Outline

Options.java

(4 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
137
Outline

Options.java

(5 of 6 )

Add a
recommendation

2007 Pearson Education,


Inc. All rights reserved.
138
Outline

Options.java

(6 of 6 )

2007 Pearson Education,


Inc. All rights reserved.
139

Software Engineering Observation 26.2

A benefit of using SessionBean properties


(rather than cookies) is that they can store any
type of object (not just Strings) as attribute
values. This provides you with increased
flexibility in maintaining client state
information.

2007 Pearson Education, Inc. All rights reserved.


140
Outline

Recommendations .
jsp

(1 of 2 )

2007 Pearson Education,


Inc. All rights reserved.
30 <ui:hyperlink action = "case1" binding = 141
31
32
"#{Recommendations.optionsLink}" id = "optionsLink"
Outline
style = "left: 24px; top: 192px; position: absolute"
33 text = "Click here to choose another language."/>
34 </ui:form>
35 </ui:body>
Recommendations .
36 </ui:html>
jsp
37 </ui:page>
38 </f:view>
39 </jsp:root>
(2 of 2 )

2007 Pearson Education,


Inc. All rights reserved.
142
Outline

Recommendations .
java

(1 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
143
Outline

Recommendations .
java

(2 of 4 )

2007 Pearson Education,


Inc. All rights reserved.
144
Outline

Recommendations .
java

(3 of 4 )

Obtains the objects


needed to retrieve
the users selections

2007 Pearson Education,


Inc. All rights reserved.
145
Outline
Creates
recommendations
for the Recommendations
user .
java

(4 of 4 )

2007 Pearson Education,


Inc. All rights reserved.

You might also like