Session 7 -Main Theme J2EE Component-Based Computing Environments
Document Sample


Application Servers
G22.3033-011
Session 7 - Main Theme
J2EE Component-Based Computing Environments
(Part II)
Dr. Jean-Claude Franchitti
New York University
Computer Science Department
Courant Institute of Mathematical Sciences 1
Agenda
DOC Architectures Detailed
OMA Services Detailed
Web Programming
WebLogic
WebSphere
Open Source J2EE Environments
JBoss
Practical Application (Plants by WebSphere)
JSP Programming
Summary
Readings
2
Assignment #5 (continued)
Summary of Previous Session
Component Technologies
Database Technology Review
EJB Component Model
J2EE Services
JNDI, JMS, JTS, CMP/BMP/JDBC, JavaMail, etc.
J2EE Web Architectures
Security in J2EE Application Servers
Structured Applications Design Tips
Summary
Readings
Assignment #5
3
Application Servers Architectures
Application Servers for Enhanced HTML (traditional)
a.k.a., Page-Based Application Servers
Mostly Used to Support Standalone Web Applications
New Generation Page-Based Script-Oriented App. Servers
First Generation Extensions (e.g., Microsoft IIS with COM+/ASP)
Servlet/JSP Environments
XSP Environment
Can now be used as front-end to enterprise applications
Hybrid development environments
Distributed Object Computing Platforms
Provide an infrastructure for distributed communications enabling
Still need to merge traditional web-oriented computing with object computing
Object Management Architectures
DOC Platform + APIs to reusable services and facilities
4
OMAs + Component Models -> J2EE, CCM, DNA
Part I
DOC Architectures Detailed
5
RPC Structure
(review)
6
CORBA Architecture Review
7
CORBA Object Activation/Method Invocation
(top layer - basic programming architecture)
8
CORBA Object Activation/Method Invocation
(middle layer - remoting architecture)
9
CORBA Object Activation/Method Invocation
(bottom layer - wire protocol architecture)
10
11
DCOM Architecture Review
12
DCOM Object Activation/Method Invocation
(top layer - basic programming architecture)
13
DCOM Object Activation/Method Invocation
(middle layer - remoting architecture)
14
DCOM Object Activation/Method Invocation
(bottom layer - wire protocol architecture)
15
Part II
OMA Services Detailed
16
CORBA OMA Services
(* items are covered in this session)
Activation Services*
CORBA POA
CORBA Lifecycle
Naming Service*
CosNaming
Directory and Trading Services*
CosTrading
Object Transaction Service (OTS)
Messaging Services
CORBA Event Service
CORBA Notification Service
17
Activation Service - CORBA POA
(Server Structure)
18
Activation Service - CORBA POA
(Server Registration)
19
Activation Service - CORBA POA
(Client Request - Initial Steps)
20
Activation Service - CORBA POA
(Client Request - Next Steps)
21
Naming Service Conceptual Architecture
(review)
22
Naming Service - CosNaming
(Binding and Resolving Names in a Naming Context)
Servant resolve(name);
Naming Context
<name1, object_ref1>
bind(name, object_ref); … Client
<namen, object_refn> object_ref
23
Naming Service - CosNaming
(Federated Naming Context)
Naming Context1
<name, object_ref>
…
Naming Context2 Naming Context3
<name, object_ref> <name, object_ref>
… …
24
Naming Service - CosNaming
(Non Persistent Naming Services Perform Best)
Remote Context Creation
70
60
50
Milliseconds
40
30
20
10
0
200 400 600 800 1000
HARDPack 2.555 2.6375 2.698333333 2.8275 2.935
VisiBroker 21.515 28.0325 41.90333333 45.44125 52.812
TAO 11.52 12.105 12.94833333 13.865 14.726
ObjectBus 59.11 60.56 59.17166667 60.07375 61.392
Num ber of Contexts
25
Naming Service - CosNaming
(Only TAO Has Nearly Constant Bind Latency)
Remote Name Binding
1000
Miliseconds
100
10
1 5000 10000 15000 20000 25000 30000 35000 40000
HARDPack 4.545 8.0087 11.6458667 15.17475 18.62976 22.1068 25.4752571 28.88025
VisiBroker 4.929 6.6575 6.22993333 7.71965 10.08208 14.5067667 15.8996286 20.664125
TAO 2.2858 2.4306 2.42653333 2.4863 2.48508 2.60353333 2.55254286 2.5722
ObjectBus 69.36 110.496 151.574667 192.532 233.0668 273.938 314.84 355.345
Number of Bindings
26
Naming Service - CosNaming
(TAO and Visibroker Achieve Nearly Constant Resolve Time)
Remote Name Resolution
9
8
7
6
Miliseconds
5
4
3
2
1
0
4000 8000 12000
HARDPack 3.679625 5.6826625 7.97755
VisiBroker 2.21074 2.2919375 2.362541667
TAO 2.1773025 2.6174125 2.387075
ObjectBus 5.48295 6.2143375 6.923641667
Num ber of Resolutions
27
Naming Service - CosNaming
(Multithreaded Naming Servers Perform Best)
Multi-client name Resolution Latency
12
10
Milliseconds
8
6
4
2
0
1 Clients 2 Clients 3 Clients 4 Clients 5 Clients
HARDPack 3.8227 4.45548 6.22214 8.31908 10.47662
VisiBroker 2.38974 2.62138 2.81726 3.49356 4.14808
TAO 2.0372 2.11244 2.36938 2.88452 3.36642
ObjectBus 4.4998 5.06372 6.67668 8.4932
28
Naming Service - CosNaming
(Memory Utilization)
Contexts (Kbytes) Names (Kbytes)
Vendor Process 0 1 100 0 1 100
TAO Naming Server 8168 8216 13000 8168 8168 8272
VisiBroker Naming Server 5336 5352 5872 5336 5352 5576
VisiBroker osagent 2208 2224 2576 2208 2224 2224
VisiBroker persistent store .686 .801 12.01 .686 .930 24.91
HARDPack Naming Server 3104 3104 3104 3104 3240 3248
ObjectBus Naming Server 3832 3832 3832 3832 3840 3928
ObjectBus rvd daemon 1928 1928 1928 1928 1928 1928
ObjectBus persistent store .976 .976 .976 .976 1.298 50.80
29
Naming Service - CosNaming
(Conclusion)
Product Context Name Name
Creation Binding Resolution
VisiBroker 3 2 1
HARDPack 1 3 3
TAO 2 1 2
ObjectBus 4 4 4
30
Trader Service - CosTrading
Trader = Automatic Yellow Pages for Services
Services Offer Interfaces and Properties
Criteria Match Clients to Appropriate Services
See http://www-mtl.mit.edu/~mvermins/corba/trader/ppframe.htm
Interface:
Admin
ImportAttributes
Link
LinkAttributes
Lookup
OfferIdIterator
OfferIterator
Proxy
Register
SupportAttributes
31
TraderComponents
J2EE OMA Services
(* items are covered in this session)
Activation Services*
RMI Activation Framework
http://www.devx.com/upload/free/features/javapro/2000/11nov00/tm0011/tm0011.asp
JavaBeans Activation Framework
Naming and Directory Service*
JNDI and JNDI SPIs for CosNaming, RMI, NIS, NDS, LDAP
Trading Service*
Jini
JTA and JTS
Messaging Services
JMS
JavaMail 32
RMI Activation Framework
(classes of the RMI activation API)
33
JavaBeans Activation Framework
(Glasgow releas of the JavaBeans Component Model)
Extensible Runtime Containment and Services Protocol
DCOM Activation Framework
Drag and Drop Subsystem for the Java Foundation Classes
JavaBeans Activation Framework (JAF)
A Data typing and command registry API
Lets users discover an arbitrary data object type (e.g., file)
Users can then lookup command applications or beans that can
process such data type (e.g., browser plug-in to view/edit file)
Can activate the command
34
Naming Conventions
(DNS v.s. NFS)
35
Directory Services
(LDAP directory attributes)
36
Using JNDI to support Mobile Agents
(Traders need to locate places where agents can migrate to)
37
Using JNDI to support Mobile Agents
(Agents have classcodes needed by the mobile agent system to execute them)
38
Using JNDI to support Mobile Agents
(Agents must be registered so they can be located as needed)
39
The Architecture of JNDI
40
JNDI Detailed Architecture
http://java.sun.com/products/jndi/serviceproviders.html
41
Jini’s Service-Based Architecture
42
Jini’s Relationship to Other Java Services
43
RMI in the Jini Environment
44
Sample Jini “Loan Approval” Service
45
RMI Activation Framework
(Illustrated RMI Activation Protocol)
46
DNA OMA Services
(* items are covered in this session)
Activation Services*
DCOM Activation Framework
Naming and Directory Service*
DCOM Class and Object Naming (i.e., CLSIDs, ProgIDs, and Monikers)
Trading Service*
Microsoft Active Directory
Transaction Service
COM+ MTS
Messaging Service
COM+ MSMQ
47
COM+ Services
(* items are covered in this session)
COM+ Catalog (v.s. Windows Registry)*
COM+ Load Balancing
COM+ In-Memory Database (IMDB)
COM+ Object Pooling
COM+ Queued Components
COM+ Events
C++ Compiler Changes
48
DCOM Class and Object Naming
(file moniker file: bind)
49
DCOM Class and Object Naming
(url moniker http:, ftp:, gopher: bind)
50
DCOM Class and Object Naming
(class moniker clsid: bind)
Display name for class monikers:
display-name = "CLSID:" string-clsid-no-curly-braces
*[";" clsid-options] ":"
clsid-options = clsid-param "=" value
clsid-param = none currently defined
C++ example (tell moniker to use an object that can read
a document instead of the document itself):
ProgIDFromCLSID( &clsid, "xyz.activator.1")
CreateClassMoniker( clsid, &pmkClass )
MkParseDisplayName( pcb,
"\\northamerica\central\employee.doc", &dwEaten,
pmkFile )
pmkFile->BindToObject( pcb, pmkClass, IID_IDispatch,
&pDisp ) 51
Trading Service - Active Directory
http://www.microsoft.com/windows2000/server/evaluation/features/dirlist.asp
52
COM+ Catalog v.s. Windows Registry
Stores COM+ application attributes, class attributes, and
computer-level attributes
Guarantees consistency among attributes
Provide common operations on top of attributes
Two different stores
COM+ registration database
Microsoft Windows Registry (HKEY_CLASSES_ROOT)
COM components that do not require new COM+ services
Type library
Interface proxy/stub registration
Unified logical view via COM+ Admin Library 53
Part III
Traditional and Java Web Programming
54
Second Generation Client/Server Architectures
(needing to be Web-enabled)
First Generation was mostly thin-clients connected
to back-end mainframe applications
55
Evolution of Multi-Tier Architectures
Traditional client-server technology
CGI frameworks
Page-based extended HTML environments
Distributed object computing platforms
Java-Based
Object Management Architectures (OMAs)
Component-based computing environments
Web Services platforms + Grid Computing + P2P
Next generation application servers (reflective,
multimedia- and agent enabled, MDA-compliant, etc.)
56
Web-Enabled Architectures
Application Servers for Enhanced HTML (traditional)
a.k.a., Page-Based Application Servers
Tag-Oriented (e.g., Macromedia ColdFusion 5.0 Server)
Script Oriented (e.g., Microsoft IIS with ASP, PHP)
Mostly Used to Support Standalone Web Applications
Typically less expensive than standalone and IDE-based servers
HTML-based development
New Generation Page-Based Script-Oriented App. Servers
First Generation Extensions (e.g., Microsoft IIS with COM+/ASP)
Servlet/JSP Environments
XSP Environment
Can now be used as front-end to enterprise applications
Hybrid development environments
57
Web and Application Services
Activation Services
Client: MIME Handler, and Applet Activation
Web Server: File-Stream, Process, Script Engine, Servlet, JSP, and EJB
Activation
Naming and Directory Service
DNS and Java-Based DNS Interfacing
NIS, NDS, LDAP
Custom Transaction Services
Based on Encina, Tuxedo, etc.
Custom Messaging Services
TIBCO
MQSeries 58
J2EE Web-Enabling Component Models
Javasoft’s Applet Tutorial:
http://java.sun.com/docs/books/tutorial/applet/TOC.html
Swing Applets:
http://java.sun.com/docs/books/tutorial/uiswing/start/swingApplet.html
Java Web Start:
http://www.javasoft.com/products/javawebstart/index.html
Servlets, Servlet filters, JSPs, XSPs, JavaBeans
Connected Devices
MIDP
WAP/WML (http://webdev.apl.jhu.edu/~rbe/kvm/)
59
Options for Session Management
Stateless Nature of Servlets and JSPs
User application state needs to be stored outside
Servlets/JSPs
User application state is referred to as “Session State”
HttpSession
One of the ways to manage session data
It is NOT the only way
Session Storage Approaches
Client-based
Server-based
Technologies
Cookies
HTTP Session
60
URL Rewriting
Using Cookies for Session Management
Approach
Data is maintained on the client by the browser on behalf of server
Cookies can persist within or across browser sessions
Not Appropriate for Large Amounts of Application Data
4K limitation
Need to split larger strings over multiple cookies, which complicates
programming
Architectural Role:
Preferred way to pass a HTTPSession ID to the Web container
Same approach can be used for any data that remains constant across the Web
application
e.g., customer ID
Eliminates the need to use URL encoding or hidden fields
Great approach for small amounts of user preference data
E.g., maintain persistent cookie with the last query used to select
products to make it possible to tailor a Product Catalog list based on
Customer past usage history
61
Cookies Architectural Pros and Cons
Pros:
Offload space and processing time to client machines
Cookies can persist within or across browser sessions
Cons:
Passing cookies back and forth is relatively expensive
Cookies are not supported by all browsers or levels of browsers
Cookies may be turned off by users for security or privacy reasons
Need to code the application to use alternative technique
Make explicit decision to only support users with cookies enabled
Other HTTP-based clients (e.g., applets) may have trouble dealing with
cookies and may restrict the servlets that they may invoke
Alternatives:
URL encoding
Equivalent data is placed in the URL query string
62
Hidden Fields
Approach
Value set on a Web page and read by servlets
Cannot be changed by the browser user
Default approach in the early days of Web development
Architectural Considerations
On many browsers, hidden fields can be seen via the
browser’s “view page source” option
Hidden fields can be used by any servlet that receives a
carried along HTTP request
If multiple browser windows are open, the hidden fields are
unique to each browser window
63
Content-Based Routing
WebSphere Edge Server Integrated Solution for
Multivendor Web Server Environments
- rea
Local and wide a load balancing
- ased quality of service routing
Content b
Web content filtering and caching
- .ibm.com/software/webservers/edgeserver/
See http://www 4
Advantage
In case of a server failure, a generic content routing cannot
reach the failed machine
Edge Server pings the servers to verify that they are
operational
Edge Server reroutes request to servers that are not
operational
Servlets and databases must be configured to run on different
servers for the rerouting to work 64
Servlet Services
HTTPSession Limitation
Only allows retrieval of HTTPSessions by servlets running on
the same JVM as the servlet that originally created that
HTTPSession
Solution does not support server independence
Session should only contain primary or key values rather than
application data
65
Session Storage
Generic Options
EJBs
Database
Serialized object file
Identifying Client Records in Database
Store unique key in a hidden field or a client-side cookie
Persistent HttpSession
Large object graphs should not be stored in HttpSession
Amount of information in HttpSession should less than 4K
WAS limits the amount of persistent information to 32K-2MB
depending on the database used
WebSphere Sessions (allow manual updates)
com.ibm.Websphere.servlet.session.IBMSession
Edge Server Approach
Session data is cached in memory
A copy of the session data is also stored in a database for availability
after a server switch
66
Session Management Review
Cookies Pros and Cons
Pros: easy to use, stored on client machines
Cons: can be turned off, unsecure, limited in size
Hidden Fields Pros and Cons
Pros: stored on client, cannot be turned off, easy to retrieve, can be larger
than cookies
Cons: unsecure, transmitted both ways, must be generated dynamically
Hidden Fields Pros and Cons
Pros: stored on server, secure, supported by Servlet API
Cons: can be a problem when sharing across servers, maintaining session
ID can be problematic (cookies, URL rewriting), can get quite large
Storing Session Data to a Database
Whenever a session started on one server may be switched to another
server and session data is used to maintain state
Storing data to a database makes it available to any server
67
Part IV
WebLogic
Also See Session 7 Handouts on:
“Deploying an EJB Application”
“Building a Stateless Session Bean”
“Using Enterprise JavaBeans”
“EJB Application Servers”
“Application Servers Comparison”
68
J2EE Support
J2EE Specifications Support
EJB, JSP, Servlets, JNDI, JDBC, JMS, JTA/JTS
RMI 1.0 Support
IIOP
HTTP
T3 (rich sockets)
Multiplexed, bi-directional, asynchronous
One socket per thread
69
Security
Secure Socket Layer
RSA Encryption
X.509 digital certificates
ACL down to the method level by users/groups
Security realms
Can import information from other
authorization/authentication systems into the ACL
Firewall tunneling via HTTP and HTTPS tunneling
Security audit and logging interfaces
70
Data Stores
RDBMS support via JDBC
OODBs (e.g., Versant, ODI)
Object relational mapping tools
(e.g., WebGain’s TOPLink)
Cache accelerators:
TimesTen’s Front-Tier
71
Supported Client Types
Thin Clients
Web Clients (e.g., HTML, WML)
Fat Clients
Programmatic Clients (e.g., Java applets, Java
standalone applications, COM clients)
Use XML/RMI to communicate with server
Client Administration
Zero Administration Client (ZAC)
72
Management
Swing-based Console
Monitoring/Update of Applications and Clusters
Viewing of Detailed Execution Information
Servlets, EJBs, JMS queues/topics
Third Party Management Framework Support via SNMP
73
JVM and Platform Certification
Platforms
Linux
IBM OS/390
Sun Solaris
NT and Windows 2000
Certified JVMs listed on the BEA Web Site
74
Tools Support
IBM VisualAge for Java
KLGroup Jprobe
WebGain Studio
Visual Café Enterprise Suite
MacroMedia DreamWeaver
Tendril Structure Builder
TOPLink O/R Mapping Tool
75
Enterprise Assurance Features
Performance
High Performance HTTP Web Server
Plugins: Netscape (NSAPI), IIS (ISAPI), Apache
Socket Handling via interrupts (performance pack)
Clustering (load balancing, automatic failover)
Reliability
Scalability
76
Application Support and Proprietary Extensions
Common logs, instrumentation, configuration, mgmt, etc.
dbKona and htmlKona (OO interface to HTML)
The WorkSpace (thread-safe hash table)
Scheduling (define actions or triggers)
File I/O (seamless manipulation of remote files)
CGI Support (to support migration of first generation apps)
Connection Filtering (block/allow connections from
clients)
77
WebLogic 6.1 Features
(historical)
Web Services (SOAP and WSDL support)
J2EE Connector Architecture 1.0
EJB 2.0, Servlet 2.3, and JSP 1.2
XML Support:
JAXP 1.1, SAX 2.0, DOM Level 2, W3C Schemas
JMS Performance Enhancements
Optional asynchronous I/O
Deployment descriptor editing utilities
Tuxedo Integration
Oracle optimizations, EJB caching improvements, etc.
78
WebLogic 7.0 – 8.1
(Features)
Web Services (SOAP and WSDL support)
J2EE Connector Architecture (J2EE CA) 1.0
EJB 2.0, Servlet 2.3, and JSP 1.2
XML Support:
JAXP 1.1, SAX 2.0, DOM Level 2, W3C Schemas
JMS Performance Enhancements
Optional asynchronous I/O
Deployment descriptor editing utilities
Tuxedo Integration
Oracle optimizations, EJB caching improvements, etc.
79
Part V
WebSphere (more in next session)
See Session 7 Handouts on:
“Application Servers Comparison”
“WebSphere by IBM”
80
WebSphere 5.0
(Features)
Full J2EE 1.3 support
Message beans and container managed messaging
Connector Architecture (JCA) to connect single-phase
resources such as CICS to two-phase resources like DB2
Web Services support
Enhanced security
WebSphere Studio Application Developer (WSAD)
Leverages IBM HTTP 2.0 service, MQSeries, and DB2
81
IBM WebSphere Application Server (WAS) 4.0
(http://www.research.ibm.com/journal/sj/373/bayeh.html)
82
IBM WebSphere Application Server (WAS) 4.0
(servlet engine)
83
IBM WebSphere Application Server (WAS) 4.0
(JavaServer subsystem)
84
WebSphere Terminology
Managed Process or Server
Each application/JMS server running in its own JVM
Node Agent
Manages servers running on a single physical machine (i.e.,
a node)
Deployment Manager
Manages multiples nodes in a distributed topology
Cell
Network of multiple nodes in a single logical
administration domain
85
WAS 5.0 Offerings
WebSphere Application Server – Express
RAD Environment for Servlets and JSP pages
J2EE 1.3 and Web Services Subset
Emphasizes Ease of Use, Small Footprint, and Pre-Canned
Applications
WAS
J2EE 1.3 (EJB 2.0 & Servlet 2.3) and Web Services
Support
Replacement for WAS 4.0 – Single-Server Edition
WAS Network Deployment (WAS-ND)
Manages Multiple Application Servers & Handles
Clustered Environments
Replacement for WAS Advanced Edition
Includes a Basic WAS with Deployment Features
Distributed System Management, Clustering, Basic Workload
86
Management, Monitoring, etc.
WAS 5.0 Offerings (cont.)
WAS Extended Deployment (WAS-XD)
Extended Version of WAS Network Deployment
Cross-Domain Failure Bypass, Dynamic Load Balancing, etc.
Optimizes Performance, Availability, and Scalability
Includes Scalability and Manageability Features
WAS Enterprise (WAS-EE): WAS-ND + WAS-XD +
PMEs
High-End Package that includes WebSphere MQ
Includes Programming Model Extensions (API and
Associated Run-Time & Mgmt. Features)
Dynamic EJBQL, Access Intent (e.g., Optimistic/Pessimistic
Concurrency Control), LE, BP Choreography, Extended
Messaging/Transactions, CORBA C++ SDK, etc.
Activity Service (JSR-95), WorkArea (JSR-149),
Internationalization Service (JSR-150)
Replacement of WAS Enterprise Edition 4.0
WAS Application Server for z/OS 87
Special Packaging Optimized for z/OS Environment
WebSphere Products
WebSphere Portal
WebSphere Commerce
WebSphere Host on Demand and Host
Publisher
WebSphere Translation Server
WebSphere Voice Products
WebSphere EveryPlace
Transcoding Publisher
etc.
88
WebSphere Management Tools
Assembly Tools
Application Assembly Tool (AAT)
Eclipse based AAT (future)
WebSphere Studio Family of Products
Enterprise Application Mgmt Tools
Browser based Admin Console
http://localhost:9090/admin
Attached either to the App Server or the Cell
Struts-based implementation
Command line tools
WSAdmin
Java APIs
All admin tools may modify configuration
documents (i.e., resources.xml, and variables.xml,
89
etc.) located under <was_root>/config
WebSphere Directions
Platform
Reach and User Experience
Business Integration
Foundation and Tools
Product Objectives
Platform for Enterprise Computing
Platform for Innovation
Help Developers Focus on Building Applications
Establish/Maintain Standards Leadership
Flexible Set of Product Configuration Options
Principles
Platform Treated as a Development Principle
IBM Leverages Core Competencies
Platform Ensures Robustness
WebSphere Used to Build Some of the Components of WebSphere
Vision
JMX
Web Services
Support for new PMEs and Enterprise Architecture Patterns 90
WebSphere in Production Deployments
91
J2EE Packaging
J2EE Application .EAR file
Application DD
EJB Module .JAR file
Enterprise Bean
EJB DD
Schema Map, Schema Attributes, Table Creation, IBM Extensions,
IBM Bindings
Web Module .WAR file
Servlet
JSP
HTML, GIF, etc.
Web DD
IBM Bindings, IBM Extensions
Client Module .JAR file
Client Class
Client DD
IBM Bindings
92
IBM Bindings, IBM Extensions
WebSphere Packaging Extensions
Sample WebSphere Options
Web Application Reloading
File Serving and Servlet Invoker by Classname
Transaction Isolation Attributes
Extensions Stored in ibm-type-ext.xmi
Type is ejb or web
Defining IBM Extensions
Use Extension Editor in WSAD
Use the AAT Extensions Tab of the Component’s Property
Sheet
93
WebSphere Packaging Bindings
Bindings are Used to Specify how Local
Names or resources (e.g., ejb-ref) are tied
into a J2EE runtime
Bindings stored in ibm-type-bnd.xmi
Type is “application”, “ejb”, or “web”
Defining IBM Bindings
Use Extension Editor in WSAD
Use the AAT when defining the resource-ref
or ejb-ref
94
Application Assembly Tool (AAT)
Used to:
Build .war and .ear files
Configure application deployment
properties and initial set of bindings
Configure application/server binding into
.ear
Can use WSAD as an alternative
Bindings have to be entered during
application installation
95
WAS Deployment Steps
Stop/Uninstall Conflicting Sample Applications
Bring up the WAS Administration Console Web Application
http://localhost:9090/admin
Select administration console checkbox in WSAD and “Run Administrative
Console” from server context menu
Define Data Source
Delete any conflicting pre-configured data sources
Pick JDBC provider and create a data source
Name used to display data source
JNDI name is critical (e.g., jdbc/PlantsByWebSphereDataSource)
Select Use data source in container managed persistence as needed
Creates associated CMP connector factory
Data source helper class name should be correct
96
WAS Deployment Steps
(continued)
Select Data Source Custom Properties
E.g., database name for Cloudscape data source
Save Configuration using Save Item in Menu Bar
Install the Application
Automatic binding generation possible
Identifies all unmapped references in the EAR (E.g., ejb-refs) and attempts to
resolve them with resources defined in the EAR
Select options in the various pages of the application installation
wizard
Click “Finish” on the final (summary) page in the wizard
Select the Save item on the menu to save the configuration
Test application: e.g., http://localhost:9080/contextroot 97
WAS Middleware Management Architecture
JMX Server
Hosts JMX model MBeans that represent managed resources in the WebSphere network
Admin Service
Provides external and remote representations of JMX server
MBeans and Information Model
Defines type space for WebSphere MBeans
Configuration Repository
Holds managed resources configuration
Administration Application and Workspace
Implements the user interface to the middleware management system
Node Agent
Provides localized management on a given node
Acts as an end-point listener to the deployment manager
Deployment Manager (or cell manager)
Provides centralized control over the deployment cells
PME Administration Extensions
98
Middleware management system extensions for Enterprise Edition
WebSphere Programming Model
See: ftp://ftp.software.ibm.com/software/websphere/partners/TheVisionForWASV5AndBeyond.pdf
99
WAS e-Business Computing Models
Multi-Tier Distributed Computing
Separation of presentation, business and data logic
Runtime component management architecture
Object identity, transaction & session management, security,
versioning, clustering, workload balancing and failover,
caching, etc.
Component Sharing
OO Modeling Compatibility
Web-Based Computing
Presentation logic relocated in the middle-tier
Uses a Tier-0 fixed-function device (i.e., Web
browser)
Other Tier-1/2 devices are supported as well
100
Implements Edge-Computing via Servlets/JSPs
WAS e-Business Computing Models
Integrated Enterprise Computing
Copes with Legacy Extensions
Integration of pre-existing applications
SAP, CICS, Oracle, IMS, Windows, DB2, Tibco,
PeopleSoft, Domino, MQSeries
Supports “incremental business process re-
engineering”
Based on Java 2 Connectors and JMS
Point-to-point asynchronous messaging,
request/response messaging, publish-subscribe
messaging
Moving towards Business Process 101
Management (BPM)
WAS e-Business Computing Models
Services-Oriented Computing
New approach to B2Bi
XML message encoding architecture + HTTP
as a communication transport
Web services are about how to access a
business service, while J2EE is about how to
implement that business service
102
WAS Integrated Computing Model
J2EE Component-Based Programming
models
Multiple Presentation Device Types
Web Services
Message-Oriented Programming
BPM
Used to script the flow of process activities
implemented as J2EE components
Legacy Integration via Java 2 Connectors and
Higher-Level Adapters
103
Application and Component Design Patterns
See http://www.ibm.com/developerworks/patterns
Thick-Client Presentation Logic
Web-Client Presentation Logic
Model-View Controller
Componentized Business Logic
Encapsulation of Persistence and Data Logic
Adapter-Based Integration
Request-Response Messaging
Publish-Subscribe Messaging
Web Services
Workflow
104
WebSphere Development Model
Create a Design Model for your Application
Develop Application Components and Organize them
in the Web Application and Module Archives
Define Deployment Policies for Components
Transactional semantics, security assumptions, extended
deployment policies, etc.
Assemble Component JARs into WARs and EJB
Modules, and create a J2EE EAR
May use application assembly tool, and/or an XML editor
to edit the J2EE XML descriptor files)
Can also use WSAD
Generate Deployment Code for Components
Includes the creation of EJB properties mappings to the
database schema
Install Application to the WebSphere Runtime
Directly on application server instance, or through Cell 105
Manager in a clustered environment
WebSphere Development Roles
Component Developer
Responsible for codifying business and presentation logic in servlets,
JSPs, and EJBs
May be split in sub-roles
Application Assembler
Responsible for assembling components into an EAR that includes all
modules, a manifest, and deployment descriptor information
(deployment policies)
Must understand overall functional objective
Works with the DBA to implement/optimize the database mapping
Application Deployer
Responsible for installing the application into the runtime, picking and
configuring the application server, and resolving dependencies
System Administrator
Responsible for configuring the application server network
Addresses failures and performance bottlenecks
Evaluates log files, test performance metrics, and monitors system
utilization
Performs capacity, integrity, and security management 106
WebSphere Development Roles
Author
Responsible for assembling static and dynamic
content
Web Application and EJB Container Provider
WAS
Operations Centers Administrators
Business Managers
etc.
107
Programming Features
J2SE 1.3 APIs
Applets
AWT/Swing
JavaBeans
I/O
Language Classes
J2SE Extensions
JCE
JSSE
PKCS
J2EE
Servlet 2.3
JSP 1.2
EJB 2.0
JDBC 2.0
JTA 1.0
JMS 1.0.3
J2EE Connector Architecture 1.0
JAAS 1.0
JAXP 1.1
JavaMail 1.2
JAF 1.0
Web Services
WebSphere Additional Functions 108
WebSphere Application Server Extension APIs
J2SE 1.3 Restrictions
J2SE 1.3 APIs
No particular WebSphere support for applets
Cannot drive AWT/Swing UIs from hosted applications
J2EE only permits AWT/Swing use of the clipboard, Swing events, and
showing windows in a J2EE client container
These features are not allowed in applet, Web, or EJB containers without
enabling privileged code
I/O operations may be restricted by file permissions
Access to system files or WebSphere runtime files is restricted
System-related runtime functions used to control ClassLoader, Security
Manager, Threads/Thread Groups, Socket Factories, etc. are restricted
Process-related thread functions should not be used
Can be supported by enabling privileged code or using Async Beans
(PME) to make WebSphere aware of the threads
Should not manipulate the garbage collector through references
Should not create in-bound socket listeners in hosted code
Should not construct an RMI server in the WAS
Avoid the direct use of J2SE security classes
109
Application clients, applets, servlets, and EJBs can only read properties
J2EE Extensions
com.ibm.websphere.servlet.cache
com.ibm.websphere.servlet.error
com.ibm.websphere.servlet.event
com.ibm.websphere.servlet.filter
com.ibm.websphere.servlet.request
Allows stream manipulation and introduces a servlet request proxy
com.ibm.websphere.servlet.response
Includes support for generating and storing responses
com.ibm.websphere.servlet.session
Session management across clusters
110
IBM WAS Persistence Extensions
Access Intent
Default is “Pessimistic Update with weakest lock at load”)
Application Profile (provides “dynamic” access intent)
EJB Persistence Support Extensions (e.g., EJB inheritance)
EJB QL Extensions (e.g., ORDER BY)
Transactions (unit-of-work scoping)
Support for JCA and JDNC-based local transactions to define
what goes on when the transaction context is “unspecified” as per
the EJB 2.0 specification
ActivitySession Service
Goal is to retain contained EJBs beyond a given transaction
111
Web Services Support
Invocation Programming Interfaces
JAX-RPC
Web Services Invocation Framework (WSIF)
Handles SOAP over HTTP/JMS
Web Services Security
SOAP-SEC
Web Services Gateway
Act as Web Services Proxies
Useful to integrate J2EE and .Net services
UDDI
112
Additional Functions
Struts and Struts Tag Library
Extension APIs
Activity Sessions
Application Profiles
Asynchronous Beans and Scheduler
Business Rules Beans
Choreography
Container Managed Messaging
Dynamic EJB Query
Internationalization Extensions
JTA Synchronization Notification
Last Agent Optimization
Staff Services
Startup Beans 113
C++ ORB
WebSphere Programming Tools
114
Eclipse Platform
Integrated Development Platform for Building
Diverse Applications
http://www.eclipse.org
Uses Standard Widget Toolkit (SWT) to look and feel like
a native application
Common definition for resources, projects, and preferences
Extensibility via Eclipse plug-ins
Basic architecture includes a small Eclipse core, and
various plugins (basic UI framework, core resource
support, version control management, java development
tools, etc.)
WebSphere Studio is Built on the Eclipse 2.0
Platform
115
WebSphere Studio
Site Developer
Intended for professional developers of dynamic Web applications and
sites
Supports servlets, JSPs, XML , and Web Services tools
Includes integrated WAS test environment and deployment automation
tools
Application Developer
Site developer + advanced Web services and EJBs
Supports application execution tracing, profiling and performance
analysis
Application Developer Integration Edition
Application Developer + full SOA development environment for
business and EAI
Includes workflow visual builder and full choreography support
Enterprise Developer
Application Developer Integration Edition + EIS creation tools
116
Part VI
Open Source J2EE Environments
(JBoss)
117
JBoss
(www.jboss.org)
Component Architecture
Basic EJB Container (low memory/disk space requirements)
Java Management Extension (JMX) Infrastructure
Plug and Play Services: JBossMQ (JMS), JBossMX JavaMail),
JBossTX (JTS/JTA), JBossSX (JAAS), JBossCX (JCA
connectivity), JBossCMP
Unique Features
Built-in SQL database server (Cloudscape not required)
Hot deploy, Runtime generated stubs/skeletons objects
(distributed invocation enablers)
See References:
118
http://www.jboss.org/testimonials.jsp
JBoss.org JBoss JMX Infrastructure
(Versions 2.4.4-2.4.10 for JVM 1.3+)
^
TomCat Servlet Container
Jetty Web Server/Servlet Container 119
JBoss 3.0.6-3.2 for JVM 1.3+
(J2EE Support)
J2EE Specifications Support
EJB, CMP 2.0, JSP 1.2, Servlets 2.3, JNDI 1.0, JDBC
2.0, JavaMail / JAF, JMS 1.0.1, JTA 1.0/JTS, JMX 1.0,
JAAS 1.0
RMI 1.0 Support
IIOP
HTTP
120
JBoss 3.0.6-3.2
(www.jboss.org)
Component Architecture
Basic EJB Container (low memory/disk space requirements)
Java Management Extension (JMX) Infrastructure
Plug and Play Services: JBossMQ (JMS), JBossMX JavaMail), JBossTX
(JTS/JTA), JBossSX (JAAS), JBossCX (JCA connectivity), JBossCMP
Unique Features
Built-in SQL database server (Cloudscape not required)
Hot deploy, Runtime generated stubs/skeletons objects (distributed invocation
enablers)
See References:
http://jboss.org/forums/forum.jsp?forum=159
Future:
4.0 version – lightweight component model & Aspect Oriented Framework
http://www.jboss.org/developers/projects/jboss/projects.jsp 121
Part VII
A Practical Application
Plants-By-WebSphere Sample
Also See:
http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/DEA2eTOC.ht
ml
http://java.sun.com/j2ee/overview.html
http://java.sun.com/j2ee/white/j2eeAnneThomas.pdf
http://java.sun.com/j2ee/white/j2ee_guide.pdf
122
What is a Component Model?
Component Model Subsumes:
Component as a packaged software object with a
standardized interface and reusable in multiple
applications
Specification
Programming Model
Deployment Model
Administration Model
Component architecture
How components interact with each other and with
software tools
123
Simplified J2EE Platform Today:
“The Whole is Much Greater than the Sum of its Parts”
124
Best Practices for Server-Side
Applications Development
125
MVC Review
Model
Only one model
Implements business logic using JavaBeans/EJBs
View
One or many window(s) into the model
Provides presentation/user manipulation via JSPs
Controller
One or more
Parses and directs user requests via servlets
126
Web Browser Clients
• Tier-0 Clients
– Presentation is handled by logic running in the Web
Application Server and rendered by the browser
– Differences in browsers may require server awareness
• Tier-1 Clients
– Commonly used for Intranet development
– Rich set of presentation features
– Rely on direct communication with business logic using IIOP
or SOAP
– Supported by libraries such as SWT and JFC/Swing
• Pervasive Devices
– WebSphere provides servlet extension that detects the client
device type and selects a presentation specific to that device.
– WebSphere Everyplace Access provides transcoding 127
technology
Architecture Design Principles
Layer the Application
Use JSPs for Presentation Only
Use Servlets as Controllers and to Maintain the
Application State
Facilitate Evolving Architectural Requirements
Facilitate Incorporation of New Technologies
Facilitate Support for Different Types of Clients
Reduce Need for Future Application Maintenance
128
User Request Processing via Servlets
Servlet gets client request
Servlet determines which program elements are
required to carry out the specified request
JavaBeans or EJBs perform the business logic
operations for the request and encapsulate the
results
Servlet selects a presentation template (JSP) to
deliver the content back to the client
JSP generates a specific response by accessing
the content available via the JavaBeans
129
JSP Design Considerations
Use Indirect Programming Model
JSP is invoked indirectly by a controller servlet
There should be no control behavior within the
JSP
The amount of Java code within the JSP should be
minimized
JSP is only there to provide a response to the client
130
Model Layer
Should be Split into
Domain Model Layer
Corresponds to the model in the MVC architecture
Infrastructure Model
Data mapping layer (persistence) that provides the
mapping between domain objects and the data sources
Data source layer obtains and saves information in a data
store
The decoupling allows reuse of domain objects
across applications
131
Controller Flow Models
Action Based Processing
One servlet for each client request
A subclass of the base Action class is created for each type of request
Used by Web Frameworks
Struts relies on a single servlet for each client request, and action
subclasses
Design enhances code testability, but it is difficult to write actions for
applications with a complex state manager
State Based Model Alternative
Current State represented by a class implementing a common interface
that defines each action/request as a method
Single HttpSession object is used to maintain the application state
Controller obtains the current state object and invokes a corresponding
action method on that state object
Controller updates the application’s state object based on the result of
the action
132
Exception Handling
Supports Graceful Recovery from Unexpected
Application Errors
Global Handling
Handling is global for the entire application
WebSphere InstallableError Handler
ErrorReporter Servlet for debugging
Error-page that routes errors on any named JSPs
Local Handling
Handling is specific to the action performed
Expected errors are handled by specific JSPs
Unexpected errors are handled by Servlet 133
Controller Design Patterns
Command Pattern
Command object corresponds to a business logic
task (i.e., action)
Command implemented as serialized objects
State Pattern
Robustly handles complex state-based application
behavior
Memento Pattern
Behavioral pattern used to take a snapshot of a
portion of an object’s state so that the object can be
restored later
May be used in Web applications to handle the
browser back button 134
An Abstract View: J2EE Patterns
135
Plants-By-WebSphere
• Plants-By-WebSphere is a Sample Shipped with WAS
– A mail-order storefront for plants, trees, and gardening tools
– Includes source code
– Meant to demonstrate a classic J2EE application
– Functional
– Logic-based
• Model-based PL Comparison Framework
– JSP Pages
– HTML pages
– Servlets
– Model Wrappers
– EJBs
– Helper Classes
136
JSP Pages
(presentation)
• cart
– Content obtained from ShoppingCart EJB
• checkout
– Credit card/shipping info gathering form
• orderdone
– Confirmation of completed order submission
• product
– View of selected item
• salesitems
– Frames component images of the main home-page logo for
the store front
• showcatalog
– Lists contents of the catalog retrieved from Inventory EJB
137
Other Pages
• index.html
– Home page: logo + navigation
• banner.html
– Standard noteback tab metaphor for
navigation
138
Servlets
• ShoppingControllerServlet
– Main point of control for user input to the
plant store Web interface
139
Model Wrappers
• CartModel
– Wrapper to ShoppingCart EJB
• CustomerModel
– Wrapper to Customer EJB
• InventoryModel
– Wrapper to Inventory EJB
• OrderModel
– Wrapper to Order EJB
140
EJBs
• Catalog
– stateless session bean, collects info from store inventory
• Customer
– CMP entity bean
• FulFillOrder
– Stateless session bean
• Inventory
– CMP entity bean
• Order
– CMP entity bean
• OrderIdGenerator
– CMP entity bean
• OrderItem
– CMP entity bean
• OrderSender
– Stateless session bean used to send a message when the order is complete
• OrderReceiver
– Message-driven bean that receives order messages and calls the FulFillOrder bean
• ShoppingCart 141
– Stateful session bean that holds the contents of the shopping cart
Helper Classes
• CustomerInfo
– Java holder object for the Customer bean
• InsufficientInventoryException
– Exception thrown by FulFillOrder bean if the order
cannot be filled
• OrderInfo
– Holder-Object for the Order bean
• StoreItem
– Holder-Object for the contents of an item in the
Catalog
• Util
– Supports various helper functions (get EJB homes,
get initial JNDI context, etc.) 142
Web Services
• PlantsByWebSphereCatalogService
– Represents the PlantByWebSphereCatalog
port-type with a SOAP binding
– Service can be used to get product information
from the Catalog
143
Engineering Approach
• Develop JSP pages and Servlets
• Use a set of wrappers to the EJBs
– Allows the Web application to be developed in
parallel with the EJBs
– Model wrappers used as temporary stand-ins to the
EJBs during the development of the web application
• Map or delegate the model objects to actual
EJBs
144
Implementation Challenges
• Transactional coordination of updates to the
database and JMS queues
– Use XA data sources to the Cloudscape database that
ships with WebSphere?
• Use of relationships
– An order aggregates multiple OrderItems
• OrderSender and FulFillOrder EJBs may need to
use the Java 2 Connector Architecture (JCA) to
connect to an underlying legacy system
• Use of a Web Service 145
Web Tier Development Process
Create projects necessary for the application
Create the home page
Create the banner and the navigation menu
Create the controller
Create the model JavaBeans
Repeat for adding additional content and pages and
updating the controller
146
Creating the Projects
Use WebSphere Studio Wizards
Web Application Project Must Reside in a J2EE
Enterprise Application Project
Create a Web Application Project (File | New | Project )
Static Web project used for creating static HTML pages
J2EE Web application project used to create dynamic content
using JSP pages and servlets as well as static content
Customize the Web Project Features
.cvsignore file
Default CSS file
Include tag libraries (JSP access, database access,
internationalization, JSP standard tag library, utility tag lib)
147
Creating the Home Page
File | New is Perspective Sensitive
Select the Web Content project folder and right click to
bring up HTML/XHTML File
Code Generation Model is not used by WSAD
The HTML/JSP editor can be used in “Source” view to
edit the file, then go back to “Design” view to see the
changes
Select a Style Sheet on the Gallery tab in the Outline
view
Import a style sheet by selecting the theme folder in the Web
project in the Navigator view, then right click on File | Import
148
Business Logic
Business logic is the set of methods used to perform a
specific business function
In OO systems, a business function is decomposed
into business objects
Business logic in the OO world amounts to:
Set of methods
Business-specific rules
Pre- and post-conditions
J2EE provides EJBs to build up business logic
149
EJB Component Model
Stateless, stateful, and persistent models
Insulated from presentation and data logic tiers
Powerful declarative transaction and security policy
PlantsByWebSphere application
EJBs can “snap-in” to the model objects
CartModel (simple shopping cart)
Stateful session bean (temporary state)
OrderModel (order placed by a customer)
Entity bean
CustomerModel (customer making an order)
Entity bean
InventoryModel (item in the store inventory)
Entity bean 150
Practical EJB Implementation Steps
Create EJB Project
EJB 2.0 includes CMR, EJB Query Language, and MDB support
Create ShoppingCart Stateful Session Bean
Create Order CMP Entity Bean
Create Utility OrderIdGenerator CMP Entity Bean
Create Container-Managed-Relationship (CMR) between
Order and OrderItem
Create other CMP Entity beans, and sessions beans
Map CMP Entity Beans to a Relational Database
Specify J2EE references to EJBs and Resources Required
by EJBs
Integrate EJBs with Web Module Model Objects 151
Stateful Session Beans
Session bean state may be maintained in the memory of the
application server
Best performance
Session bean state may be stored in the local file system
between transactions
Longer availability of session bean state
State can survive application server restarts
Activation policy refers to either of the two models above
152
Local vs. Remote Interface
Local Interface
Only accessible within the application server
Performance advantage
Simple Java by-value parameter and return value semantics
Remote Interface
Costly pass-by-value semantics for parameters and return values
Actual EJB Arctifacts
Bean class, bean (local) interface, and (local) home interface
e.g., ShoppingCartBean, ShoppingCart, ShoppingCartHome
153
Differences Between CMP 1.1 and 2.0
CMP 1.1
CMP fields placed directly in the bean
Business logic may freely access CMP fields
CMP 2.0
CMP fields may only be accessed via getters/setters
Getters and setters are created through tooling
Generated code is a subclass of the bean itself
Pattern has a more standardized structured to add-in
persistence support for CMP beans
154
Entity Bean Attributes
General Attributes
Bean class
JNDI name
Local (and remote) home interface
Local (and remote) interface
Key class
CMP Attributes
Primary key
Other fields
155
Mapping CMP Entities to a RDBMS
Schema Map Generation
Top-Down mapping
Creates EJB-to-table mapping (new table creation)
Meet-in-Middle mapping
Individual CMP fields may be mapped to individual
table columns (names do not need to match, special
converter classes are used to handle conversions, and
an EJB may map to multiple tables)
Bottom-up mapping
EJB and CMP created based on existing table
156
EJB 2.0 Query Language: EJB QL
SQL-like language for expressing selection criteria over the domain
of 2.0 CMP EJBs
Database-agnostic query language that can be mapped to virtually
any relational backend
Used to implement EJB custom finders
Look under the “Bean” tab of the EJB deployment descriptor in
WSAD and scroll down to “Queries | Add”
e.g., SELECT OBJECT(i) FROM Inventory i WHERE i.category=?1
Also used to implement ejbSelect() methods, which are EJB queries
accessible to the bean implementation only
157
Application Assembly Process
Make sure that each component in the application properly
describes any dependency it may have on other components
in the application
Assign a context root for each web module included in the
J2EE application
Synchronize security role-names across the application
Link internally satisfied dependencies of all components in
every module contained in the application
158
Part VIII
Using JavaBeans in JSPs
Custom Tag Libraries
159
Using JavaBeans in JSPs
JSPs Should not be Bogged down with Lots of Java Syntax and
Control Flow
An MVC rule of thumb…
Logic / Dynamic content should be enclosed in JavaBeans
Encapsulate dynamic content in Value Beans
Encapsulate special formatting operations in Formatter Beans or Custom Actions
JSPs and JavaBeans help build robust Web applications
Embedding JavaBeans in JSPs
Use WSAD Page Designer Wizards and dialog Windows
Use JSP Editor’s Design View instead of Script editor
Passing Data Between Servlets and JSPs
Servlet creates JavaBeans and forwards control to JSPs and passes
handles (via HttpSession or HttpServletRequest objects) to one or more
JavaBeans from which dynamic content can be extracted
160
<jsp:useBean useBean_attr_list>
JSP Tag Used to Find or Create a JavaBean
Tag generates Java code that binds a local variable to a JavaBean
Bean may be retrieved from an existing context (page, request,
session, application, etc.)
Bean may also be instantiated on demand
useBean Body May or May Not be Used
Body usually contains jsp:setProperty tags (alternative to JSP
scriptlets)
Body is only executed if the result of the useBean execution is the
creation of a new bean instance
e.g., WSAD Page Designer can be Used to Insert a
jsp:useBean Tag in a JSP
JavaBean class may be dragged from the Navigator panel to Page
Designer 161
Using JavaBeans in JSPs - Review
Advantages of Using JavaBeans and JSPs Together
Code written by JSP developer is mostly HTML
JSP developer can use jsp:useBean and jsp:getProperty tags to retrieve
dynamic content data
JSP developer does not need to know Java unless a collection is being
retrieved and must be iterated through in a scriptlet
<jsp:useBean> Tag Options
Tag specifies from which object to retrieve an existing bean
If the bean is to be constructed from a serialized file, that file must be
specified
Bean can be typed as a superclass type
Using <jsp:setProperty> and <jsp:getProperty> Tags
jsp:setProperty is infrequently used (JSP developer may decide to have a
bean property set from a browser’s request parameter instead of doing so in
a servlet)
jsp:getProperty tag used to retrieve result data from a passed bean as well
as any browser parameter values
162
JSP Custom Tags
JSP Custom Tag Concepts
Tag library descriptors (TLDs)
Tag handler interfaces and support classes
WSAD Help Perspective
Javax.servlet.jsp.tagext
Advanced Topics Covered in Next Session
Sharing of data between tags
Iterating Tags
163
JSP Custom Tags: Knowledge Required
Reasons for Using JSPs
Tag Structure
Steps for Developing Tags
Using Tags in JSP
164
JSP Custom Tags Approach
Tag Function
How a Tag Works
Processing Flow
TLD Used to Describe the Tag
Tag Handler Code Development
How a Tag is Used
Test Case
Output of Test Case
165
Using Custom Tags with JSPs
Standard JSP Actions
useBean, setProperty, getProperty
include, forward, plugin, params, param, fallback
Tags are Used to Develop and Invoke Custom
Actions
Tag Libraries are Collections of Custom Tags
JSP Tags are Sometimes Referred to as “Actions”
Action is the “function” performed by a tag
166
Why Custom Tags?
Role Based Development
Developers with various skillsets focus on the various
MVC design pattern components
Keep Java out of JSPs
Use custom tags to implement presentation logic
(conditional processing, looping, etc.)
Web designer/developer can focus on presentation
Keep Presentation out of Servlets
Java Developers are not presentation experts
Best Practice
JSP custom tags used for presentation logic
167
Sample JSP with Custom Tags
<!DOCTYPE HTML PUBLIC “-//W3C//DTD
HTML 4.01 Transitional//EN”
<HTML>
<HEAD>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@ page language=“java” session="false" %>
</HEAD>
<BODY>
<c:out value="hello"/>
</BODY>
168
Custom Tags Creation and Use
Development Phase
Tag/tag attributes design
Tag declaration in a TLD
Tag handler class development
Tag helper classes development
Use Phase
Include tag library (taglib)
Specify the attributes
Test
169
Simplified Coding of Custom Tags
WSAD Page Designer
JSP->Insert Custom
170
Custom Tags Benefits
Makes JSP Development Easier
Web Developers can Focus on Presentation Aspect
Presentation Logic Becomes Reusable
171
Tag Examples
(1) <ils:fullText />
(2) <ils:code language=“java”>
(3) <ils:iterator times=10>
<p>”Hello World.”</p>
</ils:iterator>
(4) <ils:iterator name=“list” id=“customer”
type=“domain.Customer”>
<jsp:getProperty name=“customer” property=“name” />
</ils:iterator>
172
TLD Files
XML File Containing:
XML declaration (required)
DTD declaration for the file format (required)
Tag library description
<tversion>, <jspversion>, <shortname>, <info>
Tag definition
<tag>, <name>, <tagclass>, <bodycontent>
<attribute> (<name>*, <required>)
<info>?
173
TLD Location
Implementing Classes in JAR file
TLD in META-INF Directory or SubDirectory
Implementing Classes in Web Application
TLD in WEB-INF Directory or SubDirectory
DTD Location
http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd
174
Tag Handler Class
Code Implementing a Tag
Implements One of the Following Interfaces
Javax.servlet.jsp.Tag
Javax.servlet.jsp.tagext.IterationTag (extends Tag)
Javax.servlet.jsp.tagext.BodyTag (extends IteratorTag)
Extends One of the Following Classes
Javax.servlet.jsp.tagext.TagSupport (implements IteratorTag)
Javax.servlet.jsp.tagext.BodyTagSupport(extends TagSupport and
implements BodyTag)
Tag Attributes handled with JavaBean-like setter methods
Tag Handler Class Methods
doStartTag(), doAfterBody(), doEndTag()
175
Custom Tag Error Handling
Compilation Errors
Invalid Tag format
Missing required attributes
Tag Handler JspException
Invalid values specified
176
Custom Tags Packaging
Place class files in a JAR
Import TLD into /WEB-INF/tld
Import JAR into /WEB-INF/lib
177
Example: Custom Tags in WSAD
Put Tag Handler Classes in a Java Project
Add Java Project as a Project Utility Jar to the Enterprise
Application
Update application deployment descriptor
Add Dependent JAR to the Java JAR Dependencies in the
Properties of the Web Module
Copy TLD to /WEB-INF/tld directory
178
Custom Tags Review
Advantages of Custom Tags
Makes JSPs easier to develop/test/maintain
Web developers can focus on the presentation aspects
Presentation logic becomes reusable
Custom Tag Development Steps
Tags and attributes design
TLD construction/modification
Tag handler class development
JSP test
Attribute Values Processed in Tag Handler Class via JavaBean-
Like Setter Methods
doStartTag() Method is Associated with Tag Start Processing
Taglig Directive Describes TLD Location and Specifies Tag
179
Prefix
Part IX
Advanced Java Server Pages (JSPs)
and Java Servlets
180
Objectives
Advanced JSPs
Sharing Data Between Tags
Iterating Tags
JSP Standard Tag Library (JSTL)
Servlet Filters
181
Sharing Data Between Tags
Similar to producer/consumer sharing via
<jsp:useBean> and <jsp:getProperty>
Producer:
<jsp:userBean id=“shared”
type=“com.ibm.ils.library.LoanedCopy”/>
Consumer:
<jsp:getProperty name=“shared”
property=“itemCode”/>
182
Example Tag
Producer:
<ils:now id=“rightnow”
type=“com.ibm.ils.library.TimeBean”/>
Consumer:
<jsp:getProperty name=“rightnow”
property=“time”/>
183
Sharing Mechanism
■ Producer stores object in a scope attribute
■ Producer makes stored object type available
■ Using this information, the JSP container declares a variable of the
proper type in the generated servlet code
■ Variable can then be used to handle the object read from the scope
attribute
■ Need to program a new class that extends “TagExtraInfo” and
override the getVariableInfo() method
■ Also need to add information in the TLD to associate he
TagExtraInfo with the tag handler class that defines the shared
variable
■ Container calls getVariableInfo() and looks for the
implementation class name in the TLD 184
getVariableInfo( ) Method
Public VariableInfo[] getVariableInfo(TagData data)
TagData contains attribute/value information for a given tag
instance
VariableInfo[] contains information about the scripting variables
defined with this TagExtraInfo instance
Array contains one element per variable shared
VariableInfo[] Values (can be set using a constructor in the
VariableInfo class that takes the four values as parameters)
Variable name of the share object
Class name of the share object
Boolean indicating that object was created by this tag
Variable scope (i.e., AT_BEGIN, AT_END, or NESTED)
i.e., Where the object will be declared in the generated servlet 185
TagExtraInfo Subclass Implementation Sample
package com.ibm.ils.adv.tags;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
public class NowTagExtraInfo extends TagExtraInfo {
public VariableInfo[] getVariableInfo (TagData aTagData) {
VariableInfo aInfo = new VariableInfo(
aTagData.getAttributeString(“id”),
aTagData.getAttributeString(“type”),
true,
VariableInfo.AT_END);
VariableInfo[] info = { aInfo };
return info;
}
} 186
TagExtraInfo TLD Specification
<tag>
<name>now</name>
<tagclass>com.ibm.ils.adv.tags.NowTag</tagclass>
<teiclass>com.ibm.ils.adv.tags.NowTagExtraInfo</teiclass>
<bodycontent>JSP</bodycontent>
<info>Returns current date of time</info>
<attribute>
<name>id</name>
<required>true</required>
</attribute>
<attribute>
<name>type</name>
<required>true</required>
</attribute>
</tag> 187
Tag Implementation Sample
// package and imports not included
Public class NowTag extends BodyTagSupport {
// Element attribute name
private String id;
private String type;
private Iterator iterator;
private static final String DATE_FMT = “MMMM dd, yyyy”;
private static final String TIME_FMT = “hh:mm a z”;
public void setId (String aId) { id = aId; }
public void setType (String aType) { type = aType; }
public int doStartTag() {
Date now = new Date();
TimeBean tb = new TimeBean();
SimpleDateFormat dataFmt = new SimpleDateFormat(DATE_FMT);
tb.setDate (dateFmt.format(now));
SimpleDateFormat timeFmt = new SimpleDateFormat(TIME_FMT);
tb.setTime (timeFmt.format(now));
pageContext.setAttribute(id, tb);
return SKIP_BODY
} 188
}
Using Producer / Consumer Tags
<ils:now id = “rightnow” type = “com.ibm.ils.adv.beans.TimeBean” />
(…)
<jsp:getProperty name=“rightnow” property=“date” />
(…)
<jsp:getProperty name=“rightnow” property=“time” />
(…)
189
Iterating Tags
Data to be Displayed with a JSP is often Generated by
a Servlet as a Collection (e.g., ArrayList)
Scriplets are Used to Extract the Information to
Populate each Table Row
Requires Java code within the JSP!
Alternative:
Tag that extracts each element from the collection
and makes it available to other tags
190
Scriplet Approach
<TABLE border=“1”>
<TR><TH align=“center”>Event</TH>
<jsp:useBean id=“eventlist” class = “com.ibm.ils.adv.beans.EventListBean”, scope=“request” />
<% java.util.ArrayList list = eventlist.getEventList();
for (int i=0; i<list.size(); i++) {
com.ibm.ils.adv.beans.EventBean tableRow=
(com.ibm.ils.adv.beans.EventBean) list.get(i);
%>
<TR>
<TD><%= tableRow.getEventName()%></TD>
</TR>
<%}%>
</TABLE>
191
Iterating Custom JSP Tag Approach
<TABLE border=“1”>
<TR><TH align=“center”>Event</TH>
<jsp:useBean id=“eventlist” class = “com.ibm.ils.adv.beans.EventListBean”, scope=“request” />
<ils:iterator id=“tableRow” classname=“com.ibm.ils.adv.beans.EventBean”
list=“<%= eventlist.getEventList() %>”
<TR>
<TD><jsp:getProperty name=“tableRow” property=“eventName” /></TD>
</TR>
</ils:iterator>
</TABLE>
192
Iterating Tags Implementation Mechanism
First Step: <ils:iterator …>
Initialization an setter method execution
Second Step: <ils:iterator …>
doStartTag() initializes loop, stores next element in a scope attribute,
and returns EVAL_BODY_AGAIN for first iteration or SKIP_BODY
for no iterations
Evaluate Tag Body
Third Step: (loop increment)
doAfterBody() returns SKIP_BODY to terminate loop or
EVAL_BODY_AGAIN for next iteration
Fourth Step: (loop exit)
doEndTag() gets the body content, writes to JSP Writer and returns
EVAL_PAGE
193
Iterating Tag Implementation Steps
Add Tag to TLD
Add <teiclass>
List required attributes
List attribute must be a “runtime” attribute
(<rexprvalue> tag set to true) so that it is an expression
that is evaluated at runtime
Create IteratingTagExtraInfo Class
Provides information about the shared current
element of the list to the container
Create Tag Handler Class IteratingTag 194
<ils:iterator> TLD Specification
<tag>
<name>iterator</name>
<tagclass>com.ibm.ils.adv.tags.IteratingTag</tagclass>
<teiclass>com.ibm.ils.adv.tags.IteratingTagExtraInfo</teiclass>
<bodycontent>JSP</bodycontent>
<info>Iterates over a collection</info>
<attribute><name>id</name><required>true</required></attribute>
<attribute><name>classname</name><required>true</required></attribute>
<attribute>
<name>list</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
195
IteratingTagExtraInfo Subclass Implementation Sample
package com.ibm.ils.adv.tags;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
public class IteratingTagExtraInfo extends TagExtraInfo {
public VariableInfo[] getVariableInfo (TagData aTagData) {
VariableInfo aInfo = new VariableInfo(
aTagData.getAttributeString(“id”),
aTagData.getAttributeString(“classname”),
true,
VariableInfo.NESTED);
VariableInfo[] info = { aInfo };
return info;
}
} 196
IteratingTag Implementation Sample
package com.ib.ils.adv.tags;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class IteratingTag extends BodyTagSupport {
// Element attribute name
private String id;
private String classname;
private Iterator iterator;
// constructor and setter methods setId(), setClassname() have been omitted
(…)
197
IteratingTag Implementation Sample
(continued)
(…)
public void setList (Collection aList) { // setter method for list
if (aList.size() > 0)
iterator = aList.iterator(); // Creates iterator for the list
}
public int doStartTag() { // Performs initialization
int rc = 0;
if (iterator == null) { // loop terminates if there are no elements in the list or if the iterator is null
rc = SKIP_BODY;
} else {
if (iterator.hasNext()) {
pageContext.setAttribute(id, iterator.next()); //first value in the list is placed in page context attribute
// next value retrieved by doAfterBody()
rc = EVAL_BODY_AGAIN; // evaluate body again until there are no list elements left
} else {
rc = SKIP_BODY; // skip the body when there are no more list elements
}
}
return rc;
} 198
(…)
IteratingTag Implementation Sample
(continued)
(…)
public int doAfterBody() {
int rc=0;
if (iterator.hasNext()) { // loop terminates if there are no elements in the list or if the iterator is null
// Put next element in page context name attribute
// and set rc to process body again
pageContext.setAttribute(id, iterator.next()); // next value in the list is placed in page
// context attribute
rc = EVAL_BODY_AGAIN; // evaluate body again until there are no list elements left
} else {
rc = SKIP_BODY; // skip the body when there are no more list elements
// doEndTag() will be called next
}
return rc;
}
(…)
199
IteratingTag Implementation Sample
(continued)
(…)
public int doEndTag() throws JspException {
BodyContent bc = getBodyContent();
if (bc != null) {
// Write out all looped body content (possibly over several iteration loops)
JspWriter out = getPreviousOut();
try {
out.print(bc.getString());
} catch (IOException e) {
throw new JspException(“iterator: “ + e.getMessage());
}
}
return EVAL_PAGE;
}
(…) 200
IteratingTag Implementation Sample
(continued)
(…)
public void release {
id = null;
classname = null;
iterator = null;
super.release();
}
}
201
Java Server Pages Standard Tag Library
JSTL Specification is Part of JSR-052
Core
Iteration <forEach>
Conditional <if>, <choose>, <when>, <otherwise>
Expression language
XML Processing
Parsing, XPath, XSL transformation (<x:transform>)
Data Formatting
I18N capabilities for dates, currency, and numbers
RDBMS
SQL support (<sql:query>, etc.)
202
Advanced JSP Tags Review
The TagExtraInfo Class Needs to be Extended to Provide Information
about Shared Variables to the JSP Container
The Information Specified in the VariableInfo Object Includes:
Shared variable id
Shared variable class name
Boolean flag indicating if the object referenced by the variable was created
by the tag
Variable scope
Iterating Tags Extract Elements in a Collection and Make the Current
Element of the List Available to Other Tags as a Shared Variable
The Tag Handler Class Typically Implements doStartTag() (loop
initialization), doAfterBody() (loop increment), and doEndTag() (post-
loop processing)
203
Servlet Filters
Introduced in the Servlet 2.3 API specification
Reusable components
Used to transform the content of HTTP requests,
responses and headers
Can be configured into chains of multiple filters
Indirectly invoked by a client request to a Web
resource
Handle request pre-processing, response post-
processing, request/response transformation, control
transfer, execution blocking
204
Sample Filter Uses
Authentication
Logging/Auditing
Image Conversion
Data Compression
Encryption
Tokenizing
Event Triggering
XSLT
MIME-type
Caching
205
Filter Chains and Filter Implementation
Filters may be configured in a chain
FilterChain object is used to describe the chain
Filters are invoked via nested calls
Servlet container invokes doFilter() on 1st filter
First filter invokes doFilter() on next filter, etc.
Servlet filtering also referred to as Servlet Chaining
Filter implementation (Select File -> New -> Other -> Filter)
Filter class implements javax.servlet.Filter
Filter class provides implementations for init(), doFilter(), and destroy()
methods
Filter is described in the deployment descriptor with the <filter>
element
Filter chaining configuration is described in the deployment descriptor
with the <filter-mapping> element 206
Java Servlet API Interfaces
javax.servlet.Filter
init(), doFilter() (FilterChain object passed as parameter),
destroy()
Javax.servlet.FilterConfig
FilterConfig object passed by container to filter init()
getFilterName(), getInitParameter(),
getInitParameterNames(), getServletContext()
Javax.servlet.FilterChain
doFilter()
207
Filter Descriptor Tags
<filter> (see Web Deployment Descriptor Filter page in WSAD)
<filter-name>
<filter-class>
<init-param>
<param-name*>
<filter-mapping> (order of first apparition used for chaining)
<filter-name>
<servlet-name>
<url-pattern> (first priority for matching in case of duplicates)
Servlet and URL names are mutually exclusive elements
208
Sample Filters
Logger (elapsed servlet execution time logging)
FormChecker (form syntax checker that blocks chain execution
if form is found incorrect)
Trailer (post-processing filter that adds a message at the end of
a web’s resource response page using a custom response
object)
209
Servlet Filters Review
Building a Filter Requires the Implementation of the javax.servlet.Filter
interface
The FilterChain Object Defines the Sequence of Filter Execution
The Container Passes and Object of Type FilterChain to the 1st Filter
The Execution Follows that in the Filter Mapping Elements in the Deployment
Descriptor, and the Order is Determined by te Order of Matching Filter
Mapping Elements
A Filter Can Control the Flow or Processing by note Calling the chain.doFilter()
Method
The Requested Web Resource is the Last on the Filter Chain
Typical Processing Pattern is as Follows:
Examine request headers, wrap req/resp as custom objects, invoke next filter or web
resource, process response object, throw exception as necessary
The Container Creates One Instance of a Filter for each Filter Element Defined
in the Deployment Descriptor 210
Part X
Java Server Faces, and Related Frameworks
See:
http://java.sun.com/j2ee/javaserverfaces/download.html
http://java.sun.com/j2ee/javaserverfaces
http://java.sun.com/j2ee/javaserverfaces/docs/tutorial.html
211
Java Server Faces
Simplified Server-Side UI Building
Reusable UI component assembly
Data source connections
Client-Server event wiring
JavaServer Faces Technology
APIs (UI components representation, state management, events
handling, input validation, page navigation, I18N, etc.)
JSP custom tag library to express a JavaServer Faces interface
within a JSP page
Provides a Component Model for the User Interface
212
Java Server Faces Applications
Run in a Java Servlet Container like any Other Java Web
Application
Include traditional components:
Model objects (i.e., JavaBeans)
Event Listeners
Pages (e.g., JSPs)
Server-side helper classes (e.g., database access beans)
Also include JavaServer Faces components:
Custom tag library to render UI components on a page
Custom tag library to represent event handlers, validators, etc.
UI components are represented as stateful server objects
Validators, event handlers, and navigation handlers
213
Sample JSP Page
<html> <head><title>Hello</title></head>
<body bgcolor="white">
<img src="duke.waving.gif">
<h2>My name is Duke. What is yours?</h2>
<form method="get">
<input type="text" name="username" size="25"> <p></p> <input
type="submit" value="Submit">
<input type="reset" value="Reset">
</form> <% String username = request.getParameter("username"); if (
username != null && username.length() > 0 ) { %>
<%@include file="response.jsp" %> <% } %>
</body>
214
</html>
Equivalent ServerFaces Page 1
<HTML> <HEAD> <title>Hello</title> </HEAD>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<body bgcolor="white">
<h:graphic_image id="wave_img" url="/wave.med.gif" />
<h2>My name is Duke. What is yours?</h2>
<jsp:useBean id="UserNameBean" class="helloDuke.UserNameBean" scope="session"/>
<f:use_faces><h:form id="helloForm" formName="helloForm">
<h:input_text id="username" modelReference="UserNameBean.userName"/>
<h:command_button id="submit“ label="Submit“ commandName="submit" />
</h:form>
</f:use_faces>
</body>
</HTML>
215
Equivalent ServerFaces Response Page
<HTML><HEAD> <title>Hello</title> </HEAD>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<body bgcolor="white">
<h:graphic_image id="wave_img" url="/wave.med.gif" />
<f:use_faces>
<h:form id="responseform" formName="responseform">
<h2>Hi, <h:output_text id="userLabel"
modelReference="UserNameBean.userName" />
</h2> <h:command_button id="back“ label="Back" commandName="back"/>
<p>
</h:form>
</f:use_faces>
</body>
</HTML> 216
Related Java Web Frameworks
Sun ONE Application Framework (ex-JATO)
Extends MVC using a J2EE-based design pattern that comes with an extendable but
ready-to-use implementation
Jakarta Struts (http://jakarta.apache.org/struts/)
Encapsulates the User-Interface at the form or page level
Custom controller (i.e., ActionServlet that delegates to Action objects based on an
ActionMapping table, Action objects are passed an ActionForm)
Interacts with standard data access technology for the model (e.g., EJB, JDBC, O-R
bridges, etc.), and the view (e.g., JavaServer Pages, Velocity Templates, XSLT, etc.)
Relationship to JavaServer Faces
Can use JavaServer Faces component-level functionalities (e.g., rendering, events,
etc.) within a page
Can keep using their own application model for higher-level functionality (e.g.,
forms, actions)
Note: Web Frameworks may not be based on the servlet API:
217
Maverick, WebWork, Tapestry framework, etc.
Part XI
Conclusion
218
Summary
CORBA, RMI/RMI IIOP, and COM+ have comparable
architectures based on RPC support layers
Activation and naming services provided by CORBA 3, J2EE,
and DNA platforms have different architectures and APIs.
WebSphere and WebLogic provide a comprehensive and
competitive J2EE solutions
JBoss provides a resource and platform effective alternative to
higher end J2EE application servers
JBoss is an open source solution use by many small enterprises
today
219
Readings
Readings
Building J2EE Applications with IBM WebSphere:
Chapters 9-15, 17, 19-23
Microsoft .Net Distributed Applications:
Sections on COM+ Services (continued)
Handouts posted on the course web site
Explore J2EE environments
Read related white papers/documentation on the J2EE
environments
220
Project Frameworks
Project Frameworks Setup (ongoing)
Apache Web Server (version 1.3.28/2.0.47, www.apache.org)
Perl (version 5.8.0, www.perl.com)
Microsoft IIS with COM+/.Net and ASP
Sun One Active Server Pages 4.0
http://wwws.sun.com/software/chilisoft/index.html
Apache Tomcat
Macromedia JRun4
Apache Cocoon 2/XSP
Visibroker, Orbacus
RMI-IIOP
WebLogic 8.1, WebSphere 5.0, JBoss
221
Assignment
Assignment:
Explore the textbooks’ references to Application Server
technology (continued)
#5 (continued): Due date is 11/05/01
Session 7 special assignment: Write a short report that
documents your findings and recommendations with respect
to selection criteria in support of development environments
for the application servers covered in this session (due along
with assignments #5a and #5b)
222
Next Session:
J2EE Component-Based
Computing Environments (Part III)
Other J2EE Application Servers
SunOne, Inprise, Sybase EAServer, etc.
Enterprise Component Development
with J2EE
Designing J2EE Component-Based
ArchitecturesOther J2EE Application
Servers
223
Get documents about "