Developing Web
Applications
Peter Komisar © Conestoga
College version 1.0 Fall / 2007
Reference:
Third Draft Document for Review, Sept. 17,2007,
SG24-7501-00 'Rational Application Developer V7 Programming
Guide'.
This is a synopsis
of information found in the latter part of
the 12th chapter, 'Developing Web Applications with Servlets
and JSPs' found in the third draft Document for Review, dated
October 23, SG24-7501-00 Rational Application Developer V7
Programming Guide. It has been prepared for private academic
purposes and is not an effort to publish the contained material.
Any anonymous
quotes are from the
above noted reference.
Introduction to J2EE
Web Applications & Review
J2EE supplies a framework for building and deploying
Web applications in Java. The key building blocks are
servlets and JSPs on which other technologies like Struts
and Java Server Faces are based.
Their primary function is to process web requests and
responses. JSPs combine HTML and Java code which
is compiled into a servlet.
JSPs and servlets are typically part of the
'presentation
layer' of a larger business application. Core business
functions are usually separated out into a
clearly defined
set of interfaces, so that these components can be maintained
independently.This business logic will often be contained
in Enterprise JavaBeans.
Struts, JavaServer Faces (JSF), various JSP tag
libraries
and other technologies extend the JSP and servlets framework
in different ways to improve aspects of J2EE Web development.
//
JSF facilitates the creation of reusable UI components.
Using JSPs with servlets and HTML is the simplest option
for building J2EE Web applications.
//
see figure 12-1 in the pdf
J2EE
applications
At the top level, the J2EE specification describes two
application types, the web application stored in a WAR
file and an enterprise application stored in an EAR file
or enterprise Application Resource file.
The WAR and the EAR are zip files with predefined
directory structures. Web applications generally contain
Web components while the enterprise application
contains the entire application and may itself include
a number of WAR files.
Enterprise Applications
An enterprise application 'project' holds the set of
resources needed to deploy a J2EE enterprise
application to Application Server and may contain
- Web application modules
- EJB modules
- Java libraries
- application client modules
- a deployment descriptor // application.xml
- must be in the META-INF directory
- guides the installation and execution
On deployment, the EAR file is extracted by the
application server and each of the individual
components, EJB modules, WAR files and any
associated JAR files are deployed. Shared JAR
files are scoped to be available for the whole
application.
//
while typical EJBs don't have to be used
"A Web application server publishes the contents
of a WAR file under a defined URL root (called a
context root) and then directs web requests to the
right resources returning the response to the requestor. "
Requests may be mapped to:
- a simple static resource //
html files & images
- a specific JSP or servlet class //
dynamic resources
When
a Web request is received, the application
server looks at the context root of the URL to identify
which WAR the request is intended for, then the server
looks at the contents after the root to identify which
resource to send the request to.
//
root identifies the app
Each WAR file has meta information that guides the
application server in its deployment and execution of
the servlets and JSPs within the Web application.
//
WARs standard patterns allow porting apps
// between J2EE compliant web servers
Because elements in WARs follow a standard pattern,
Web applications can be ported between different Web
application servers. All J2EE compliant servlet containers,
including the test Web environment provided by RAD
support this specified structure.
The web.xml File
The deployment descriptor for the web application is
called web.xml. The Web application server uses it to
guide the configuration and and running of the Web
application. The deployment descriptor holds:
- configuration info for starting
servlets
- mapping information for servlets & JSPs
- security information // who can access what
- filters //
allow calling code before processing a request
- listeners // allow calling code on certain events
- configuration parameters
- for servlets or the application as a whole.
The Required WEB-INF Directory
The only requirement for the
Web application
directory structure is to have a WEB-INF directory.
Resources are accessible by clients which are usually
web browsers via a URL. Following the contents of
EARs and WARs are listed in detail.
Enterprise Application Archive
(EAR)
- /META-INF/application.xml - deployment
descriptor
- .jar - Utility Java libraries
- .jar - Enterprise JavaBean (EJB) JARs
- .war - Web Applications (WAR files).
Web
Application Resource (WAR)
- /WEB-INF/web.xml - deployment descriptor
- /WEB-INF/classes/* - Java classes used by application
- /WEB-INF/lib/* - Java libraries used by application
- /*.html, *.css, ... - HTML files, templates, style sheets
- other files accessible as Web resources including
- jsps, jsp tag libraries
- html, images,sounds, etc.
The Primary Web Component Classes
- HttpServlet (extends
Servlet) //
entry point for request
- doGet( ), doPost( ) and other methods
- invokes response logic
- HttpJspServlet
(extends Servlet)
- a JSP is automatically compiled into a class extension.
- It runs like a normal servlet
- its entry point is the _jspService( ) method.
-
HttpRequest (extends Request)
- accesses request information
- HttpResponse
(extends Response)
- wraps the response to the request
- HttpSession
- stores for the duration of a users session
- RequestDispatcher
- used to redirect requests to another servlet
JSPs
JSPs allowing mix Java code and HTML. On deployment
or when the first page request occurs, this is decided in the
configuration file, the JSP is compiled into a servlet class.
The combined HTML and Java scriptlets are expressed in
the _jspService method which loads the HttpResponse
variable.
Combining too much complex Java code with HTML may
create very complicated JSP files which should be avoided.
Custom
Tags
Custom JSP tag libraries may be used to avoid complexity.
Tags are defined that initiate calls to a Java class. These
classes implement the Tag, BodyTag or IterationTag interfaces.
found in the javax.servlet.jsp.tagext package.
Each tag library is defined by a .tld file. The tld file includes
the location and content of the taglib class file. A reference to
this file needs to be included in the deployment descriptor.
JavaServer
Pages Standard Template Library (JSTL)
The JavaServer Pages Standard Template Library provides
tags to handle common, simple operations required in most
JSP programming tasks.
Some Common Tag Functions
- looping
- internationalization
- XML manipulation
- SQL result set processing
//
Example The RedBank application uses JSTL tags
// to display
tables and add URLs to a page
Model-View-Controller
pattern
The MVC concept is used to separate business logic
(model) from presentation logic (view). This allows the
view to be changed with impacting the business logic
behind it. Also, many
applications may have multiple
views of the same business model. Separating views
allows the easy addition of new views.
This separation is also popularly referred to as 'layering'
where there is a model layer and a view layer.
//
a.k.a 'layering
In addition the controller layer sits between the two,
"intercepting requests
from the view (or presentation)
layer and mapping them to calls on the business
model
and then returning the response".
The controller layer allows the other views to be free
from flow control and mapping code.
There are other MVC variations built on Servlets
and JSPs including JavaServer Faces (JSF) and
Struts.
Eclipse vs RAD 7 in the Web Builder Department
The text features RAD 7's Web builder tools. Native
Eclipse tools for building web associated components
is available at the following link:
Eclipse Web Builder Tools Site
http://www.eclipse.org/webtools/
Because we in this, the first pass at this course are
bound quite tightly to the IBM Redbook, we are going
to look at the RAD 7 tools for this section. This gives
us ready made examples to highlight the key aspects
of web component features.
Key RAD 7 Web Development Tools
- Web perspective and views
- Web Site Navigation Designer
- Web Diagram
- Page Designer
- Page templates
- CSS Designer
- Security Editor
- File creation wizards
Web Perspective
and Views
"The Web perspective and its supporting views is designed
to help Web developers build and edit Web resources, such
as servlets, JSPs, html pages, style sheets, and images, as
well as the deployment descriptor files."
Opening the Web Perspective
Select Window → Open Perspective → Web
The Web Perspective Views
- Colors view
- to select cell, text, table and tag colors
- Console view
- system output from running processes
- Gallery view
- image, sound, style sheets libraries
- Links view
- with reference to the Page Designer view
- shows the links out from this file &
- elements in the Web project that link to it.
- Navigator view
- a project and folder view of the workspace
- Outline view
- an outline of the file being viewed.
- For html and JSP shows
- tag hierarchy around the cursor position.
- Selecting a tag moves the cursor to the selected element
- Page Data view
- when editing JSP files
- lists page / scripting variables available
- Page
Designer
- WYSIWYG JSP and HTML editor
- three tabs
- Design
- Source
- Preview
- shows a final page facsimile
- Palette view
- a list of html items in drawers
- drag and drop onto pages.
- // for JSPs and HTML pages
- Problems view
- lists outstanding errors, warnings or info messages
- Project
Explorer view
- shows the hierarchy of all
- workspace projects, folders and files
- focused for the Web perspective
- for easy web project navigating
- Properties
view
- Shows properties
- of the currently selected item in the main editor.
- Quick Edit
view
- enables quick JavaScript inserts
- for example 'onClick'.
- Servers view
- used to start or stop test servers while debugging.
- Snippets view
- for editing small code bits
- for example,
- adding / editing actions assigned to tags.
- Snippets view items
- can be drag and dropped
- into the Quick Edit view.
- Styles view
- edit and apply pre-built and user-defined
- styles sheets to html elements and files.
- Tasks view
- a list of things to be done in the workspace.
- Java code comment text tags can be configured
- to automatically add items to the Tasks list
//
see Window → Preferences then Java →
// Compiler → Task Tags to edit these
tags
- Thumbnails
view
- iconic view of Gallery folder contents
Web Site
Navigation Designer
"The Web Site Navigation Designer is provided to
simplify and speed up the creation of the entire Web
site navigation and can launch wizards to facilitate
the creation of html pages and JSPs."
The tool views the whole Web site while enabling
adding, deleting pages, and moving pages within
in the site.
"This tool is especially useful for building pages in a
Web application that uses a page template."
Application flow can be laid out visually and rearranged
as required. Once flow is established pages can be
built based on the design.
website-config.xml
Site design information is stored in the website-config.xml
which enables automatic generation of navigation links.
Changes are automatically factored into links.
//
also provides 'page trails' ->
// page
hierarchy to the one currently shown
To launch the Web Site Designer
- double-click Web Site Navigation
- found in the root of the Web project folder.
Web
Diagram
The Web Diagram supplies another view of the Web
application showing pages, links and the page variables.
When used with Struts or JavaServer Faces the view
can include extra information linking pages and data
together.
//
not used in the RAD Redbank example
Page
Designer
Page Designer is the primary editor for building
HTML, XHTML, JSPs, and JSF source code.
It provides three page representations:
- Design //
WYSIWYG environment to design in
- Source // source code
- Preview: //
facsimile of web browser display
Design Techniques Suggested in the IBM Redbook
Work in the Design tab, build HTML contents by dragging
items from the Palette view and arranging them with the
mouse or editing properties from the Properties tab.
Navigate quickly to another related tag via the Outline
view. Change details in the Source tab. Use Preview
tab throughout the process.
Importing HTML
Where HTML content is provided, import these files,
using the context menu on the target directory:
- Select File → Import →
General → File System
- and browsing to the new file and clicking Import.
//
the imported file opened into Page Designer has all
// editing features available
Page
Templates
"A page template contains common areas that you want to
appear on all pages, and content areas which are intended
to be unique on each page." . . . providing "a
common look
and feel for a Web project."
- IBM Redbook
//
a kind of stencil or branding element
Page templates are created in the The Page Template File
creation wizard. Once created the file can be modified in
Page Designer. The page templates are stored as *.htpl files.
//
htpl for html pages and *.jtpl files for JSP pages.
Page Template Features
1.
Page template changes reflect in pages using that template.
2. Templates to an entire web project, individual pages, and
groups of pages, or applied to an entire Web project.
3. Areas can be marked as read-only preventing users from
modifying these areas.
On Template Creation
- the user is prompted
- a dynamic page template
- // uses Struts-Tiles tech dynamically
changeable
- or a design time template.
- // when deployed and running can't be
changed
- // uses conventional servlet libraries
CSS
Designer // another build technique suggested
It is possible to create a default style sheet when creating
a new project and there are several samples included with
Application Developer. The Redbook suggests it is a good
idea is to decide on the overall theme (color, fonts) for your
Web application in the beginning and create the style sheet
at the start of the development effort. Then, HTML and JSP
files created will have a consistent look.
Style sheets are commonly kept in the WebContent/theme
folder.
"The CSS Designer is used to modify cascading style sheet
*.css files. It provides two panels, the right hand side showing
all the text types and their respective fonts, sizes, and colors
which are all editable. On the left hand side, a sample of how
the various settings will look. Changes are immediately applied
to the Page Designer if the HTML file is linked to the CSS file."
Security Editor
The Security Editor is a new enhancement with Application
Developer V7.0. It provides a wizard to specify security
groups within a Web application and the URLs that group
has access to."
//
see pdf for more details
File Creation
Wizards
File wizards create quick
skeletons of the file types required.
Selecting Wizards
File → New → Other --> Select a Wizard
--> expand the Web folder --> select file type
Available Wizards
- CSS
- creates a new cascading style sheet
- Dynamic Web
Project
- creates a new Web project
- includes
- features the project use &
- page templates
- Filter
- creates a skeleton Java class
- for a J2EE filter
- //
The wizard updates web.xml file with the filter details
- Filter Mapping
- creates a set of URLs to map a J2EE filter
- result is stored in the deployment descriptor
- Javascript
- creates a new Javascript file
- in a specified folder.
- Life-cycle
Listener
- creates
an event listener
- // example--> HttpSessionListener
- adds a reference to the
deployment descriptor.
- Security
Constraint
- populates the <security-constraint> element
- in the deployment descriptor
- contains:
- a set of URLs
- a set of http methods
- members of particular security role
- Security Role
- adds a <security-role> element
- to the deployment descriptor.
- Servlet
- creates a skeleton servlet class
- adds the servlet to the deployment descriptor
- Servlet
Mapping
- creates a new URL to servlet mapping
- adds it to the deployment descriptor
- Static Web
Project
- builds a Web project
- holds only static pages
- Web Diagram
- creates an empty web diagram
- the user can place existing pages
- and show existing page relationships
- Web Page
- creates an HTML or JSP file
- in a specified folder
- option to create a large number of page templates
- Web Page
Template
- creates a new page template file
- with option to create from a page template
- or create as a JSP Fragment, and
- define the markup language
- HTML, HTML Frameset, Compact HTML,
- XHTML, XHTML Frameset, and WML 1.3.
- optionally create a new from an existing page template
- In addition, templates containing:
- Faces Components
- Template containing only HTML
- Template containing JSP
//
Skipping Summary of New Features // see pdf for details
RedBank Application Design
This section adds a web front-end to the Java application
we saw created in the Java Application chapter. This is
done using JSPs and servlets.
Model
//
ITSOBank is the facade and also a singleton design
The model for the RedBank project is the the Java
code that were exampled earlier. ITSOBank acts as
a 'facade' to expose the other components involved.
The main ITSOBank object is a 'singleton' a design
where a single object is accessed a static public
method called getBank.
The ITSOBank object itself is composed of the other
business objects such as Customer, Account, and
Transaction.
//
see the pdf for a simplified UML class diagram of the model.
Data
Storage
This model uses Java HashMaps to store data. In a
real world model persistence would be achieved using
databases. In the EJB chapter the back end is made
robust by storing data in a database mediated by
Enterprise JavaBeans.
View Layer
The view layer is made up of four html files and the
same number of JSP files. The application home page
is the index.html containing a link to the three html pages,
rates.html, insurance.html, and redbank.html.
Home index.html links
- static
HTML pages // no
form entry fields
- rates.html
- index.html
- insurance.html
- dynamic
pages
- redbank.html
- has a form for customer ID
- accesses customer services
- such as
- accessing balance
- performing transactions
- //
security re: logon & password not covered here
- redbank.html takes the user to listAccounts.jsp
- listAccounts.jsp
shows
- customer’s details
- a list of accounts
- a logout button.
- selecting an accounts sends the user to
- accountDetails.jsp
shows
- selected account balance
- a transactions form
- the current account number
- balance
- the List TransActions Option sends
If
anything goes wrong the showException.jsp
is shown.
//
see pdf diagram
Controller Layer // UML sequence
diagrams
The controller layer implements two strategies using
five servlets:
- ListAccounts
- Get the list of accounts for one customer.
- AccountDetails
- Displays the account balance and
- the selection of operations:
- List transactions
- deposit
- withdraw
- transfer
- Logout
- Invalidate the session data.
- PerformTransaction
- Performs the selected operation calling action
- ListTransactions
- Deposit
- Withdraw
- Transfer.
- UpdateCustomer
- update customer information.
"The
first three servlets, use a simple function call from the
servlet to the model classes to implement their controller
logic and then use the RequestDispatcher to forward control
onto another JSP or html resource."
Using the Command Design Pattern
"PerformTransaction uses a different implementation pattern.
It acts as a front controller, simply receiving the HTTP request
and passing it to the appropriate control action object. These
objects are responsible for carrying out the control of the
//
Note the extra layer where the ListTransactionsCommand
// takes over the execution of the
command.
Application Implementation
Implementing the application is described
in the IBM
Redbook in the following steps.
Steps for Creating a Web
Application
- Creating
the Web project
- Web project directory structure
- Importing the RedBank model
- Defining the Web site navigation and appearance
- Developing the static Web resources
- Developing the dynamic Web resources
- Working with JSPs
Creating the Web Project // J2EE Hallmarks
To demonstrate more features, a dynamic Web
project is created rather than a static one.
A big difference in a web application vs the Java
application we were using earlier is the introduction
of a web server that will host our JSPs and servlets.
Another important point is to note that the WAR archive
file is placed inside an Enterprise EAR archive file in
compliance with the of the J2EE specification for
enterprise applications.
//
first check that Web capabilities are enabled.
- Select Windows → Preferences
- expand General →Capabilities -->
- ensure options
- basic, typical and advanced are selected.
Creating a Web
Project Steps
- Selecting Window → Open Perspective → Web.
- Select File → New → Project. // In the New Project dialog
- Select Web → Dynamic Web Project
- click Next.
- Enter in the New Dynamic Web Project Dialog:
- RAD7BankBasicWeb // in the name field.
- Project contents --> Select Use Default //
default
- // specifies where the project files to be located
- Target Runtime --> Select
- WebSphere Application Server v6.1 //
default.
- shows supported test
environments
- those installed will be displayed
- Use WebSphere Application Server V6.1 Test Environment.
- Under Configurations
- select <custom> //
default.
- lets user make pre-defined
project configurations .
- Select Add module to an EAR project //
default.
// "Dynamic Web Projects, run exclusively
within an enterprise
// application. For this reason, you
have to either
create a new
// EAR project or select an existing
project."
- EAR Project Name --> RAD7BankBasicEAR
- Add was selected
- so the wizard creates a new EAR project.
- In the Project Facets dialog -->
- select the features for:
- Default Style Sheet
- Design-Time Page Template support
- JSTL
- Web Site Navigation
- WebSphere Web (Co-existence)
- WebSphere Web (Extended)
- From this dialog you may -->
- save the configuration for future projects.
- click Save, enter:
- a configuration name
- a description
- // see diagram,saved configurations are
available for subsequent projects
- In the Web Module page -->
- accept the default options
- The settings here are:
- Context Root:
RAD7BankBasicWeb
- context root defines the URL base for the Web app
- the root part of the URI
- under which all app resources are placed
- from where they are later referenced
- also the top level directory for the Web app
- when deployed to an application server.
- Content
Directory: WebContent
- specifies a directory in the WAR
- where files will be stored
- All the contents of the WEB-INF directory
- html, JSPs, images and any other files
- are contained under this directory.
- Java Source Directory: src
- the directory where Java source code
- used by the web application is stored.
- the default value is src
- Click Next to accept the default values.
- In the Select a Page template, Web Site dialog
- leave cleared the field
- 'Use a default Page template for the Web Site'
- This dialog allows selecting page templates
// a
new default template is created after the Web project is created.
- Click Finish //
the Dynamic Web Project is created.
- //
The Web Diagram is opened automatically
Web Project Directory Structure
The Web project directory structure is shown for the
above build in the IBM Redbook pdf in Figure 12-15.
The Web Project Main Folders
- Deployment Descriptor
- an abstracted view of the web.xml
file's contents
- includes sub folders for primary
components
- Servlets
- Servlet Mappings
- Filters
- Filter Mappings
- Listeners
- Security and References.
- Web Site Navigation Wizard
- Clicking starts a tool
- for
editing the page navigation structure.
- Java Resources: src
- Java source code, for
- classes, JavaBeans, and servlets.
- When
resources are added to a Web project,
- they are
automatically compiled
- generated
class files are added to
- the
WebContent\WEB-INF\classes folder.
- WebContent
- folder holding WAR file contents
- the WAR is deployed to the server.
- It contains all the Web resources,
- needed for the application including:
- compiled Java classes
- servlets
- html files
- JSPs
- graphics
Assignment
You will have to do this exercise in RAD 7. Build a blank
dynamic Web Project as is described in the note or the
IBM Redbook pdf. Submit a screenshot the expanded
view of the directory structure as is shown in Fig 12-15
in the Redbook pdf.