g22 3033 011 c71 - nyu.edu · script oriented (e.g., microsoft iis with asp, php) mostly used to...
Post on 07-Jun-2020
1 Views
Preview:
TRANSCRIPT
1
1
Application Servers G22.3033-011
Session 7 - Main ThemeJ2EE Component-Based Computing Environments
(Part II)
Dr. Jean-Claude Franchitti
New York UniversityComputer Science Department
Courant Institute of Mathematical Sciences
2
AgendaDOC Architectures Detailed OMA Services DetailedWeb ProgrammingWebLogicWebSphereOpen Source J2EE Environments
JBoss
Practical Application (Plants by WebSphere)JSP ProgrammingSummaryReadingsAssignment #5 (continued)
2
3
Summary of Previous SessionComponent TechnologiesDatabase Technology ReviewEJB Component ModelJ2EE Services
JNDI, JMS, JTS, CMP/BMP/JDBC, JavaMail, etc.J2EE Web ArchitecturesSecurity in J2EE Application ServersStructured Applications Design TipsSummaryReadingsAssignment #5
4
Application Servers ArchitecturesApplication Servers for Enhanced HTML (traditional)
a.k.a., Page-Based Application ServersMostly Used to Support Standalone Web Applications
New Generation Page-Based Script-Oriented App. ServersFirst Generation Extensions (e.g., Microsoft IIS with COM+/ASP)Servlet/JSP EnvironmentsXSP EnvironmentCan now be used as front-end to enterprise applications Hybrid development environments
Distributed Object Computing PlatformsProvide an infrastructure for distributed communications enabling Still need to merge traditional web-oriented computing with object computing
Object Management ArchitecturesDOC Platform + APIs to reusable services and facilities
OMAs + Component Models -> J2EE, CCM, DNA
3
5
Part I
DOC Architectures Detailed
6
RPC Structure(review)
4
7
CORBA Architecture Review
8
CORBA Object Activation/Method Invocation(top layer - basic programming architecture)
5
9
CORBA Object Activation/Method Invocation(middle layer - remoting architecture)
10
CORBA Object Activation/Method Invocation(bottom layer - wire protocol architecture)
6
11
12
DCOM Architecture Review
7
13
DCOM Object Activation/Method Invocation(top layer - basic programming architecture)
14
DCOM Object Activation/Method Invocation(middle layer - remoting architecture)
8
15
DCOM Object Activation/Method Invocation(bottom layer - wire protocol architecture)
16
Part II
OMA Services Detailed
9
17
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 ServiceCORBA Notification Service
18
Activation Service - CORBA POA(Server Structure)
10
19
Activation Service - CORBA POA(Server Registration)
20
Activation Service - CORBA POA(Client Request - Initial Steps)
11
21
Activation Service - CORBA POA(Client Request - Next Steps)
22
Naming Service Conceptual Architecture(review)
12
23
Naming Service - CosNaming(Binding and Resolving Names in a Naming Context)
Naming Context
<name1, object_ref1>…
<namen, object_refn>
Servant
Clientbind(name, object_ref);
resolve(name);
object_ref
24
Naming Service - CosNaming(Federated Naming Context)
Naming Context3
<name, object_ref>…
Naming Context2
<name, object_ref>…
Naming Context1
<name, object_ref> …
13
25
Naming Service - CosNaming(Non Persistent Naming Services Perform Best)
Remote Context Creation
0
10
20
30
40
50
60
70
Number of Contexts
Mill
isec
onds
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
200 400 600 800 1000
26
Naming Service - CosNaming(Only TAO Has Nearly Constant Bind Latency)
Remote Name Binding
1
10
100
1000
Number of Bindings
Mili
seco
nds
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
5000 10000 15000 20000 25000 30000 35000 40000
14
27
Naming Service - CosNaming(TAO and Visibroker Achieve Nearly Constant Resolve Time)
Remote Name Resolution
0
1
2
3
4
5
6
7
8
9
Number of Resolutions
Mili
seco
nds
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
4000 8000 12000
28
Naming Service - CosNaming(Multithreaded Naming Servers Perform Best)
Multi-client name Resolution Latency
0
2
4
6
8
10
12
Mill
isec
onds
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
1 Clients 2 Clients 3 Clients 4 Clients 5 Clients
15
29
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 8272VisiBroker Naming Server 5336 5352 5872 5336 5352 5576VisiBroker osagent 2208 2224 2576 2208 2224 2224VisiBroker persistent store .686 .801 12.01 .686 .930 24.91HARDPack Naming Server 3104 3104 3104 3104 3240 3248ObjectBus Naming Server 3832 3832 3832 3832 3840 3928ObjectBus rvd daemon 1928 1928 1928 1928 1928 1928
ObjectBus persistent store .976 .976 .976 .976 1.298 50.80
30
Naming Service - CosNaming(Conclusion)
Product ContextCreation
NameBinding
NameResolution
VisiBroker 3 2 1HARDPack 1 3 3
TAO 2 1 2
ObjectBus 4 4 4
16
31
Trader Service - CosTradingTrader = Automatic Yellow Pages for ServicesServices Offer Interfaces and PropertiesCriteria Match Clients to Appropriate ServicesSee http://www-mtl.mit.edu/~mvermins/corba/trader/ppframe.htmInterface:
AdminImportAttributesLinkLinkAttributesLookupOfferIdIteratorOfferIteratorProxyRegisterSupportAttributesTraderComponents
32
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 JTSMessaging Services
JMSJavaMail
17
33
RMI Activation Framework(classes of the RMI activation API)
34
JavaBeans Activation Framework(Glasgow releas of the JavaBeans Component Model)
Extensible Runtime Containment and Services ProtocolDCOM Activation Framework
Drag and Drop Subsystem for the Java Foundation ClassesJavaBeans Activation Framework (JAF)
A Data typing and command registry APILets 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
18
35
Naming Conventions(DNS v.s. NFS)
36
Directory Services(LDAP directory attributes)
19
37
Using JNDI to support Mobile Agents(Traders need to locate places where agents can migrate to)
38
Using JNDI to support Mobile Agents(Agents have classcodes needed by the mobile agent system to execute them)
20
39
Using JNDI to support Mobile Agents(Agents must be registered so they can be located as needed)
40
The Architecture of JNDI
21
41
JNDI Detailed Architecturehttp://java.sun.com/products/jndi/serviceproviders.html
42
Jini’s Service-Based Architecture
22
43
Jini’s Relationship to Other Java Services
44
RMI in the Jini Environment
23
45
Sample Jini “Loan Approval” Service
46
RMI Activation Framework(Illustrated RMI Activation Protocol)
24
47
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 ServiceCOM+ MTS
Messaging ServiceCOM+ MSMQ
48
COM+ Services(* items are covered in this session)
COM+ Catalog (v.s. Windows Registry)*COM+ Load BalancingCOM+ In-Memory Database (IMDB)COM+ Object PoolingCOM+ Queued ComponentsCOM+ EventsC++ Compiler Changes
25
49
DCOM Class and Object Naming(file moniker file: bind)
50
DCOM Class and Object Naming(url moniker http:, ftp:, gopher: bind)
26
51
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 "=" valueclsid-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 )
52
Trading Service - Active Directoryhttp://www.microsoft.com/windows2000/server/evaluation/features/dirlist.asp
27
53
COM+ Catalog v.s. Windows Registry
Stores COM+ application attributes, class attributes, and computer-level attributesGuarantees consistency among attributesProvide common operations on top of attributesTwo different stores
COM+ registration databaseMicrosoft Windows Registry (HKEY_CLASSES_ROOT)
COM components that do not require new COM+ servicesType libraryInterface proxy/stub registration
Unified logical view via COM+ Admin Library
54
Part III
Traditional and Java Web Programming
28
55
Second Generation Client/Server Architectures(needing to be Web-enabled)
First Generation was mostly thin-clients connected to back-end mainframe applications
56
Evolution of Multi-Tier Architectures
Traditional client-server technologyCGI frameworksPage-based extended HTML environmentsDistributed object computing platformsJava-BasedObject Management Architectures (OMAs)Component-based computing environmentsWeb Services platforms + Grid Computing + P2PNext generation application servers (reflective, multimedia- and agent enabled, MDA-compliant, etc.)
29
57
Web-Enabled ArchitecturesApplication Servers for Enhanced HTML (traditional)
a.k.a., Page-Based Application ServersTag-Oriented (e.g., Macromedia ColdFusion 5.0 Server)Script Oriented (e.g., Microsoft IIS with ASP, PHP)Mostly Used to Support Standalone Web ApplicationsTypically less expensive than standalone and IDE-based serversHTML-based development
New Generation Page-Based Script-Oriented App. ServersFirst Generation Extensions (e.g., Microsoft IIS with COM+/ASP)Servlet/JSP EnvironmentsXSP EnvironmentCan now be used as front-end to enterprise applications Hybrid development environments
58
Web and Application Services
Activation ServicesClient: MIME Handler, and Applet ActivationWeb Server: File-Stream, Process, Script Engine, Servlet, JSP, and EJB Activation
Naming and Directory ServiceDNS and Java-Based DNS InterfacingNIS, NDS, LDAP
Custom Transaction ServicesBased on Encina, Tuxedo, etc.
Custom Messaging ServicesTIBCO
MQSeries
30
59
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, JavaBeansConnected Devices
MIDPWAP/WML (http://webdev.apl.jhu.edu/~rbe/kvm/)
60
Options for Session ManagementStateless Nature of Servlets and JSPs
User application state needs to be stored outside Servlets/JSPsUser application state is referred to as “Session State”
HttpSessionOne of the ways to manage session dataIt is NOT the only way
Session Storage ApproachesClient-basedServer-based
TechnologiesCookiesHTTP SessionURL Rewriting
31
61
Using Cookies for Session ManagementApproach
Data is maintained on the client by the browser on behalf of serverCookies can persist within or across browser sessions
Not Appropriate for Large Amounts of Application Data4K limitationNeed to split larger strings over multiple cookies, which complicates programming
Architectural Role:Preferred way to pass a HTTPSession ID to the Web containerSame approach can be used for any data that remains constant across the Web application
e.g., customer IDEliminates the need to use URL encoding or hidden fieldsGreat 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
62
Cookies Architectural Pros and Cons
Pros:Offload space and processing time to client machinesCookies can persist within or across browser sessions
Cons:Passing cookies back and forth is relatively expensiveCookies are not supported by all browsers or levels of browsersCookies may be turned off by users for security or privacy reasons
Need to code the application to use alternative techniqueMake 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
32
63
Hidden Fields Approach
Value set on a Web page and read by servletsCannot be changed by the browser userDefault approach in the early days of Web development
Architectural ConsiderationsOn many browsers, hidden fields can be seen via the browser’s “view page source” optionHidden fields can be used by any servlet that receives a carried along HTTP requestIf multiple browser windows are open, the hidden fields are unique to each browser window
64
Content-Based Routing WebSphere Edge Server Integrated Solution for Multivendor Web Server Environments
Local and wide- area load balancingContent- based quality of service routingWeb content filtering and cachingSee http://www- 4.ibm.com/software/webservers/edgeserver/
AdvantageIn case of a server failure, a generic content routing cannot reach the failed machineEdge Server pings the servers to verify that they are operationalEdge Server reroutes request to servers that are not operationalServlets and databases must be configured to run on different servers for the rerouting to work
33
65
Servlet Services HTTPSession Limitation
Only allows retrieval of HTTPSessions by servlets running on the same JVM as the servlet that originally created that HTTPSessionSolution does not support server independenceSession should only contain primary or key values rather than application data
66
Session StorageGeneric Options
EJBsDatabaseSerialized object file
Identifying Client Records in DatabaseStore unique key in a hidden field or a client-side cookie
Persistent HttpSessionLarge object graphs should not be stored in HttpSessionAmount of information in HttpSession should less than 4KWAS 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 ApproachSession data is cached in memoryA copy of the session data is also stored in a database for availability after a server switch
34
67
Session Management Review Cookies Pros and Cons
Pros: easy to use, stored on client machinesCons: can be turned off, unsecure, limited in size
Hidden Fields Pros and ConsPros: stored on client, cannot be turned off, easy to retrieve, can be larger than cookiesCons: unsecure, transmitted both ways, must be generated dynamically
Hidden Fields Pros and ConsPros: stored on server, secure, supported by Servlet APICons: 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 DatabaseWhenever a session started on one server may be switched to another server and session data is used to maintain stateStoring data to a database makes it available to any server
68
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”
35
69
J2EE Support
J2EE Specifications SupportEJB, JSP, Servlets, JNDI, JDBC, JMS, JTA/JTS
RMI 1.0 SupportIIOPHTTPT3 (rich sockets)
Multiplexed, bi-directional, asynchronousOne socket per thread
70
Security
Secure Socket LayerRSA EncryptionX.509 digital certificatesACL down to the method level by users/groupsSecurity realms
Can import information from other authorization/authentication systems into the ACL
Firewall tunneling via HTTP and HTTPS tunnelingSecurity audit and logging interfaces
36
71
Data Stores
RDBMS support via JDBCOODBs (e.g., Versant, ODI)Object relational mapping tools
(e.g., WebGain’s TOPLink)Cache accelerators:
TimesTen’s Front-Tier
72
Supported Client Types
Thin ClientsWeb Clients (e.g., HTML, WML)
Fat ClientsProgrammatic Clients (e.g., Java applets, Java standalone applications, COM clients)Use XML/RMI to communicate with server
Client AdministrationZero Administration Client (ZAC)
37
73
Management
Swing-based ConsoleMonitoring/Update of Applications and ClustersViewing of Detailed Execution Information
Servlets, EJBs, JMS queues/topicsThird Party Management Framework Support via SNMP
74
JVM and Platform Certification
PlatformsLinuxIBM OS/390Sun SolarisNT and Windows 2000
Certified JVMs listed on the BEA Web Site
38
75
Tools Support
IBM VisualAge for JavaKLGroup JprobeWebGain Studio
Visual Café Enterprise SuiteMacroMedia DreamWeaverTendril Structure BuilderTOPLink O/R Mapping Tool
76
Enterprise Assurance Features
PerformanceHigh Performance HTTP Web ServerPlugins: Netscape (NSAPI), IIS (ISAPI), ApacheSocket Handling via interrupts (performance pack)Clustering (load balancing, automatic failover)
ReliabilityScalability
39
77
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)
78
WebLogic 6.1 Features(historical)
Web Services (SOAP and WSDL support)J2EE Connector Architecture 1.0EJB 2.0, Servlet 2.3, and JSP 1.2XML Support:
JAXP 1.1, SAX 2.0, DOM Level 2, W3C SchemasJMS Performance Enhancements
Optional asynchronous I/ODeployment descriptor editing utilities
Tuxedo IntegrationOracle optimizations, EJB caching improvements, etc.
40
79
WebLogic 7.0 – 8.1(Features)
Web Services (SOAP and WSDL support)J2EE Connector Architecture (J2EE CA) 1.0EJB 2.0, Servlet 2.3, and JSP 1.2XML Support:
JAXP 1.1, SAX 2.0, DOM Level 2, W3C Schemas
JMS Performance EnhancementsOptional asynchronous I/ODeployment descriptor editing utilities
Tuxedo IntegrationOracle optimizations, EJB caching improvements, etc.
80
Part V
WebSphere (more in next session)
See Session 7 Handouts on:
“Application Servers Comparison”“WebSphere by IBM”
41
81
WebSphere 5.0(Features)
Full J2EE 1.3 supportMessage beans and container managed messagingConnector Architecture (JCA) to connect single-phase resources such as CICS to two-phase resources like DB2Web Services supportEnhanced securityWebSphere Studio Application Developer (WSAD)Leverages IBM HTTP 2.0 service, MQSeries, and DB2
82
IBM WebSphere Application Server (WAS) 4.0(http://www.research.ibm.com/journal/sj/373/bayeh.html)
42
83
IBM WebSphere Application Server (WAS) 4.0(servlet engine)
84
IBM WebSphere Application Server (WAS) 4.0(JavaServer subsystem)
43
85
WebSphere TerminologyManaged Process or Server
Each application/JMS server running in its own JVM
Node AgentManages servers running on a single physical machine (i.e., a node)
Deployment ManagerManages multiples nodes in a distributed topology
CellNetwork of multiple nodes in a single logical administration domain
86
WAS 5.0 OfferingsWebSphere Application Server – Express
RAD Environment for Servlets and JSP pagesJ2EE 1.3 and Web Services SubsetEmphasizes Ease of Use, Small Footprint, and Pre-Canned Applications
WASJ2EE 1.3 (EJB 2.0 & Servlet 2.3) and Web Services SupportReplacement for WAS 4.0 – Single-Server Edition
WAS Network Deployment (WAS-ND)Manages Multiple Application Servers & Handles Clustered EnvironmentsReplacement for WAS Advanced EditionIncludes a Basic WAS with Deployment Features
Distributed System Management, Clustering, Basic Workload Management, Monitoring, etc.
44
87
WAS 5.0 Offerings (cont.)WAS Extended Deployment (WAS-XD)
Extended Version of WAS Network DeploymentCross-Domain Failure Bypass, Dynamic Load Balancing, etc.Optimizes Performance, Availability, and Scalability
Includes Scalability and Manageability FeaturesWAS Enterprise (WAS-EE): WAS-ND + WAS-XD + PMEs
High-End Package that includes WebSphere MQIncludes 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.0WAS Application Server for z/OS
Special Packaging Optimized for z/OS Environment
88
WebSphere ProductsWebSphere PortalWebSphere CommerceWebSphere Host on Demand and Host PublisherWebSphere Translation ServerWebSphere Voice ProductsWebSphere EveryPlaceTranscoding Publisheretc.
45
89
WebSphere Management ToolsAssembly Tools
Application Assembly Tool (AAT)Eclipse based AAT (future)WebSphere Studio Family of Products
Enterprise Application Mgmt ToolsBrowser based Admin Console
http://localhost:9090/adminAttached either to the App Server or the CellStruts-based implementation
Command line toolsWSAdmin
Java APIsAll admin tools may modify configuration documents (i.e., resources.xml, and variables.xml, etc.) located under <was_root>/config
90
WebSphere DirectionsPlatform
Reach and User ExperienceBusiness IntegrationFoundation and Tools
Product ObjectivesPlatform for Enterprise ComputingPlatform for InnovationHelp Developers Focus on Building ApplicationsEstablish/Maintain Standards LeadershipFlexible Set of Product Configuration Options
PrinciplesPlatform Treated as a Development PrincipleIBM Leverages Core CompetenciesPlatform Ensures RobustnessWebSphere Used to Build Some of the Components of WebSphere
VisionJMXWeb ServicesSupport for new PMEs and Enterprise Architecture Patterns
46
91
WebSphere in Production Deployments
92
J2EE PackagingJ2EE Application .EAR file
Application DDEJB Module .JAR file
Enterprise BeanEJB DDSchema Map, Schema Attributes, Table Creation, IBM Extensions, IBM Bindings
Web Module .WAR fileServletJSPHTML, GIF, etc.Web DDIBM Bindings, IBM Extensions
Client Module .JAR fileClient ClassClient DDIBM Bindings
IBM Bindings, IBM Extensions
47
93
WebSphere Packaging Extensions
Sample WebSphere OptionsWeb Application ReloadingFile Serving and Servlet Invoker by ClassnameTransaction Isolation Attributes
Extensions Stored in ibm-type-ext.xmiType is ejb or web
Defining IBM ExtensionsUse Extension Editor in WSADUse the AAT Extensions Tab of the Component’s Property Sheet
94
WebSphere Packaging BindingsBindings are Used to Specify how Local Names or resources (e.g., ejb-ref) are tied into a J2EE runtimeBindings stored in ibm-type-bnd.xmi
Type is “application”, “ejb”, or “web”Defining IBM Bindings
Use Extension Editor in WSADUse the AAT when defining the resource-ref or ejb-ref
48
95
Application Assembly Tool (AAT)Used to:
Build .war and .ear filesConfigure application deployment properties and initial set of bindingsConfigure application/server binding into .ear
Can use WSAD as an alternativeBindings have to be entered during application installation
96
WAS Deployment StepsStop/Uninstall Conflicting Sample ApplicationsBring up the WAS Administration Console Web Application
http://localhost:9090/adminSelect administration console checkbox in WSAD and “Run Administrative Console” from server context menu
Define Data SourceDelete any conflicting pre-configured data sourcesPick JDBC provider and create a data source
Name used to display data sourceJNDI name is critical (e.g., jdbc/PlantsByWebSphereDataSource)
Select Use data source in container managed persistence as neededCreates associated CMP connector factory
Data source helper class name should be correct
49
97
WAS Deployment Steps(continued)
Select Data Source Custom PropertiesE.g., database name for Cloudscape data source
Save Configuration using Save Item in Menu BarInstall the Application
Automatic binding generation possibleIdentifies 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 wizardClick “Finish” on the final (summary) page in the wizardSelect the Save item on the menu to save the configuration
Test application: e.g., http://localhost:9080/contextroot
98
WAS Middleware Management ArchitectureJMX Server
Hosts JMX model MBeans that represent managed resources in the WebSphere network
Admin ServiceProvides external and remote representations of JMX server
MBeans and Information ModelDefines type space for WebSphere MBeans
Configuration RepositoryHolds managed resources configuration
Administration Application and WorkspaceImplements the user interface to the middleware management system
Node AgentProvides localized management on a given nodeActs as an end-point listener to the deployment manager
Deployment Manager (or cell manager)Provides centralized control over the deployment cells
PME Administration ExtensionsMiddleware management system extensions for Enterprise Edition
50
99
WebSphere Programming Model
See: ftp://ftp.software.ibm.com/software/websphere/partners/TheVisionForWASV5AndBeyond.pdf
100
WAS e-Business Computing ModelsMulti-Tier Distributed Computing
Separation of presentation, business and data logicRuntime component management architecture
Object identity, transaction & session management, security, versioning, clustering, workload balancing and failover, caching, etc.
Component SharingOO Modeling Compatibility
Web-Based ComputingPresentation logic relocated in the middle-tierUses a Tier-0 fixed-function device (i.e., Web browser)Other Tier-1/2 devices are supported as wellImplements Edge-Computing via Servlets/JSPs
51
101
WAS e-Business Computing ModelsIntegrated Enterprise Computing
Copes with Legacy ExtensionsIntegration 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 Management (BPM)
102
WAS e-Business Computing ModelsServices-Oriented Computing
New approach to B2BiXML message encoding architecture + HTTP as a communication transportWeb services are about how to access a business service, while J2EE is about how to implement that business service
52
103
WAS Integrated Computing ModelJ2EE Component-Based Programming modelsMultiple Presentation Device TypesWeb ServicesMessage-Oriented ProgrammingBPM
Used to script the flow of process activities implemented as J2EE components
Legacy Integration via Java 2 Connectors and Higher-Level Adapters
104
Application and Component Design Patterns
See http://www.ibm.com/developerworks/patternsThick-Client Presentation LogicWeb-Client Presentation LogicModel-View ControllerComponentized Business LogicEncapsulation of Persistence and Data LogicAdapter-Based IntegrationRequest-Response MessagingPublish-Subscribe MessagingWeb ServicesWorkflow
53
105
WebSphere Development ModelCreate a Design Model for your ApplicationDevelop Application Components and Organize them in the Web Application and Module ArchivesDefine 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 ComponentsIncludes the creation of EJB properties mappings to the database schema
Install Application to the WebSphere RuntimeDirectly on application server instance, or through Cell Manager in a clustered environment
106
WebSphere Development RolesComponent Developer
Responsible for codifying business and presentation logic in servlets, JSPs, and EJBsMay be split in sub-roles
Application AssemblerResponsible for assembling components into an EAR that includes all modules, a manifest, and deployment descriptor information (deployment policies)Must understand overall functional objectiveWorks with the DBA to implement/optimize the database mapping
Application DeployerResponsible for installing the application into the runtime, picking and configuring the application server, and resolving dependencies
System AdministratorResponsible for configuring the application server networkAddresses failures and performance bottlenecksEvaluates log files, test performance metrics, and monitors system utilizationPerforms capacity, integrity, and security management
54
107
WebSphere Development RolesAuthor
Responsible for assembling static and dynamic content
Web Application and EJB Container ProviderWAS
Operations Centers AdministratorsBusiness Managersetc.
108
Programming FeaturesJ2SE 1.3 APIs
AppletsAWT/SwingJavaBeansI/OLanguage Classes
J2SE ExtensionsJCEJSSEPKCS
J2EEServlet 2.3JSP 1.2EJB 2.0JDBC 2.0JTA 1.0JMS 1.0.3J2EE Connector Architecture 1.0JAAS 1.0JAXP 1.1JavaMail 1.2JAF 1.0
Web ServicesWebSphere Additional FunctionsWebSphere Application Server Extension APIs
55
109
J2SE 1.3 RestrictionsJ2SE 1.3 APIs
No particular WebSphere support for appletsCannot 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 containerThese features are not allowed in applet, Web, or EJB containers without enabling privileged code
I/O operations may be restricted by file permissionsAccess 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 restrictedProcess-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 referencesShould not create in-bound socket listeners in hosted codeShould not construct an RMI server in the WASAvoid the direct use of J2SE security classesApplication clients, applets, servlets, and EJBs can only read properties
110
J2EE Extensions
com.ibm.websphere.servlet.cachecom.ibm.websphere.servlet.errorcom.ibm.websphere.servlet.eventcom.ibm.websphere.servlet.filtercom.ibm.websphere.servlet.request
Allows stream manipulation and introduces a servlet request proxy
com.ibm.websphere.servlet.responseIncludes support for generating and storing responses
com.ibm.websphere.servlet.sessionSession management across clusters
56
111
IBM WAS Persistence ExtensionsAccess 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 ServiceGoal is to retain contained EJBs beyond a given transaction
112
Web Services SupportInvocation Programming Interfaces
JAX-RPCWeb Services Invocation Framework (WSIF)
Handles SOAP over HTTP/JMSWeb Services Security
SOAP-SECWeb Services Gateway
Act as Web Services ProxiesUseful to integrate J2EE and .Net services
UDDI
57
113
Additional FunctionsStruts and Struts Tag LibraryExtension APIs
Activity SessionsApplication ProfilesAsynchronous Beans and SchedulerBusiness Rules BeansChoreographyContainer Managed MessagingDynamic EJB QueryInternationalization ExtensionsJTA Synchronization NotificationLast Agent OptimizationStaff ServicesStartup BeansC++ ORB
114
WebSphere Programming Tools
58
115
Eclipse Platform
Integrated Development Platform for Building Diverse Applications
http://www.eclipse.orgUses Standard Widget Toolkit (SWT) to look and feel like a native applicationCommon definition for resources, projects, and preferencesExtensibility via Eclipse plug-insBasic 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
116
WebSphere StudioSite Developer
Intended for professional developers of dynamic Web applications and sitesSupports servlets, JSPs, XML , and Web Services toolsIncludes integrated WAS test environment and deployment automation tools
Application DeveloperSite developer + advanced Web services and EJBsSupports application execution tracing, profiling and performance analysis
Application Developer Integration EditionApplication Developer + full SOA development environment for business and EAIIncludes workflow visual builder and full choreography support
Enterprise DeveloperApplication Developer Integration Edition + EIS creation tools
59
117
Part VI
Open Source J2EE Environments(JBoss)
118
JBoss(www.jboss.org)
Component ArchitectureBasic EJB Container (low memory/disk space requirements)Java Management Extension (JMX) InfrastructurePlug and Play Services: JBossMQ (JMS), JBossMX JavaMail), JBossTX (JTS/JTA), JBossSX (JAAS), JBossCX (JCA connectivity), JBossCMP
Unique FeaturesBuilt-in SQL database server (Cloudscape not required)Hot deploy, Runtime generated stubs/skeletons objects (distributed invocation enablers)
See References:http://www.jboss.org/testimonials.jsp
60
119
JBoss.org JBoss JMX Infrastructure(Versions 2.4.4-2.4.10 for JVM 1.3+)
^TomCat Servlet Container
Jetty Web Server/Servlet Container
120
JBoss 3.0.6-3.2 for JVM 1.3+(J2EE Support)
J2EE Specifications SupportEJB, 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 SupportIIOPHTTP
61
121
JBoss 3.0.6-3.2(www.jboss.org)
Component ArchitectureBasic EJB Container (low memory/disk space requirements)Java Management Extension (JMX) InfrastructurePlug and Play Services: JBossMQ (JMS), JBossMX JavaMail), JBossTX (JTS/JTA), JBossSX (JAAS), JBossCX (JCA connectivity), JBossCMP
Unique FeaturesBuilt-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 Frameworkhttp://www.jboss.org/developers/projects/jboss/projects.jsp
122
Part VII
A Practical ApplicationPlants-By-WebSphere Sample
Also See: http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/DEA2eTOC.ht
mlhttp://java.sun.com/j2ee/overview.html
http://java.sun.com/j2ee/white/j2eeAnneThomas.pdfhttp://java.sun.com/j2ee/white/j2ee_guide.pdf
62
123
What is a Component Model?
Component Model Subsumes:Component as a packaged software object with a standardized interface and reusable in multiple applications
SpecificationProgramming ModelDeployment ModelAdministration Model
Component architectureHow components interact with each other and with software tools
124
Simplified J2EE Platform Today: “The Whole is Much Greater than the Sum of its Parts”
63
125
Best Practices for Server-Side Applications Development
126
MVC Review
ModelOnly one modelImplements business logic using JavaBeans/EJBs
ViewOne or many window(s) into the modelProvides presentation/user manipulation via JSPs
ControllerOne or more Parses and directs user requests via servlets
64
127
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
technology
128
Architecture Design Principles
Layer the ApplicationUse JSPs for Presentation OnlyUse Servlets as Controllers and to Maintain the Application StateFacilitate Evolving Architectural RequirementsFacilitate Incorporation of New TechnologiesFacilitate Support for Different Types of ClientsReduce Need for Future Application Maintenance
65
129
User Request Processing via Servlets
Servlet gets client requestServlet determines which program elements are required to carry out the specified requestJavaBeans or EJBs perform the business logic operations for the request and encapsulate the resultsServlet selects a presentation template (JSP) to deliver the content back to the clientJSP generates a specific response by accessing the content available via the JavaBeans
130
JSP Design Considerations
Use Indirect Programming ModelJSP 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 minimizedJSP is only there to provide a response to the client
66
131
Model Layer
Should be Split into Domain Model Layer
Corresponds to the model in the MVC architecture
Infrastructure ModelData mapping layer (persistence) that provides the mapping between domain objects and the data sourcesData source layer obtains and saves information in a data store
The decoupling allows reuse of domain objects across applications
132
Controller Flow Models
Action Based ProcessingOne servlet for each client requestA subclass of the base Action class is created for each type of requestUsed 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 AlternativeCurrent State represented by a class implementing a common interface that defines each action/request as a methodSingle HttpSession object is used to maintain the application stateController obtains the current state object and invokes a corresponding action method on that state objectController updates the application’s state object based on the result of the action
67
133
Exception HandlingSupports Graceful Recovery from Unexpected Application ErrorsGlobal Handling
Handling is global for the entire applicationWebSphere InstallableError HandlerErrorReporter Servlet for debuggingError-page that routes errors on any named JSPs
Local HandlingHandling is specific to the action performedExpected errors are handled by specific JSPsUnexpected errors are handled by Servlet
134
Controller Design PatternsCommand Pattern
Command object corresponds to a business logic task (i.e., action)Command implemented as serialized objects
State PatternRobustly handles complex state-based application behavior
Memento PatternBehavioral pattern used to take a snapshot of a portion of an object’s state so that the object can be restored laterMay be used in Web applications to handle the browser back button
68
135
An Abstract View: J2EE Patterns
136
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
69
137
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
138
Other Pages
• index.html– Home page: logo + navigation
• banner.html– Standard noteback tab metaphor for
navigation
70
139
Servlets
• ShoppingControllerServlet– Main point of control for user input to the
plant store Web interface
140
Model Wrappers
• CartModel– Wrapper to ShoppingCart EJB
• CustomerModel– Wrapper to Customer EJB
• InventoryModel– Wrapper to Inventory EJB
• OrderModel– Wrapper to Order EJB
71
141
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
– Stateful session bean that holds the contents of the shopping cart
142
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.)
72
143
Web Services
• PlantsByWebSphereCatalogService– Represents the PlantByWebSphereCatalog
port-type with a SOAP binding– Service can be used to get product information
from the Catalog
144
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
73
145
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
146
Web Tier Development Process
Create projects necessary for the applicationCreate the home pageCreate the banner and the navigation menuCreate the controllerCreate the model JavaBeansRepeat for adding additional content and pages and updating the controller
74
147
Creating the ProjectsUse WebSphere Studio WizardsWeb Application Project Must Reside in a J2EE Enterprise Application ProjectCreate a Web Application Project (File | New | Project )
Static Web project used for creating static HTML pagesJ2EE Web application project used to create dynamic content using JSP pages and servlets as well as static content
Customize the Web Project Features .cvsignore fileDefault CSS fileInclude tag libraries (JSP access, database access, internationalization, JSP standard tag library, utility tag lib)
148
Creating the Home PageFile | New is Perspective SensitiveSelect the Web Content project folder and right click to bring up HTML/XHTML FileCode Generation Model is not used by WSADThe HTML/JSP editor can be used in “Source” view to edit the file, then go back to “Design” view to see the changesSelect 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
75
149
Business Logic
Business logic is the set of methods used to perform a specific business functionIn OO systems, a business function is decomposed into business objectsBusiness logic in the OO world amounts to:
Set of methodsBusiness-specific rulesPre- and post-conditions
J2EE provides EJBs to build up business logic
150
EJB Component ModelStateless, stateful, and persistent modelsInsulated from presentation and data logic tiersPowerful declarative transaction and security policyPlantsByWebSphere application
EJBs can “snap-in” to the model objectsCartModel (simple shopping cart)
Stateful session bean (temporary state)OrderModel (order placed by a customer)
Entity beanCustomerModel (customer making an order)
Entity beanInventoryModel (item in the store inventory)
Entity bean
76
151
Practical EJB Implementation StepsCreate EJB Project
EJB 2.0 includes CMR, EJB Query Language, and MDB support
Create ShoppingCart Stateful Session BeanCreate Order CMP Entity BeanCreate Utility OrderIdGenerator CMP Entity BeanCreate Container-Managed-Relationship (CMR) between Order and OrderItemCreate other CMP Entity beans, and sessions beansMap CMP Entity Beans to a Relational DatabaseSpecify J2EE references to EJBs and Resources Required by EJBsIntegrate EJBs with Web Module Model Objects
152
Stateful Session Beans
Session bean state may be maintained in the memory of the application server
Best performanceSession bean state may be stored in the local file system between transactions
Longer availability of session bean stateState can survive application server restarts
Activation policy refers to either of the two models above
77
153
Local vs. Remote Interface
Local InterfaceOnly accessible within the application serverPerformance advantageSimple Java by-value parameter and return value semantics
Remote InterfaceCostly pass-by-value semantics for parameters and return values
Actual EJB ArctifactsBean class, bean (local) interface, and (local) home interfacee.g., ShoppingCartBean, ShoppingCart, ShoppingCartHome
154
Differences Between CMP 1.1 and 2.0
CMP 1.1CMP fields placed directly in the beanBusiness logic may freely access CMP fields
CMP 2.0CMP fields may only be accessed via getters/settersGetters and setters are created through toolingGenerated code is a subclass of the bean itselfPattern has a more standardized structured to add-in persistence support for CMP beans
78
155
Entity Bean Attributes
General AttributesBean classJNDI nameLocal (and remote) home interfaceLocal (and remote) interfaceKey class
CMP AttributesPrimary keyOther fields
156
Mapping CMP Entities to a RDBMS
Schema Map GenerationTop-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 mappingEJB and CMP created based on existing table
79
157
EJB 2.0 Query Language: EJB QL
SQL-like language for expressing selection criteria over the domain of 2.0 CMP EJBsDatabase-agnostic query language that can be mapped to virtually any relational backendUsed 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
158
Application Assembly Process
Make sure that each component in the application properly describes any dependency it may have on other components in the applicationAssign a context root for each web module included in the J2EE applicationSynchronize security role-names across the applicationLink internally satisfied dependencies of all components in every module contained in the application
80
159
Part VIII
Using JavaBeans in JSPsCustom Tag Libraries
160
Using JavaBeans in JSPsJSPs 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 JavaBeansEncapsulate 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 JSPsUse WSAD Page Designer Wizards and dialog Windows
Use JSP Editor’s Design View instead of Script editor
Passing Data Between Servlets and JSPsServlet 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
81
161
<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 UsedBody 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
162
Using JavaBeans in JSPs - ReviewAdvantages of Using JavaBeans and JSPs Together
Code written by JSP developer is mostly HTMLJSP developer can use jsp:useBean and jsp:getProperty tags to retrieve dynamic content dataJSP developer does not need to know Java unless a collection is being retrieved and must be iterated through in a scriptlet
<jsp:useBean> Tag OptionsTag specifies from which object to retrieve an existing beanIf the bean is to be constructed from a serialized file, that file must be specifiedBean can be typed as a superclass type
Using <jsp:setProperty> and <jsp:getProperty> Tagsjsp: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
82
163
JSP Custom Tags
JSP Custom Tag ConceptsTag library descriptors (TLDs)Tag handler interfaces and support classes
WSAD Help PerspectiveJavax.servlet.jsp.tagext
Advanced Topics Covered in Next SessionSharing of data between tagsIterating Tags
164
JSP Custom Tags: Knowledge Required
Reasons for Using JSPsTag StructureSteps for Developing TagsUsing Tags in JSP
83
165
JSP Custom Tags Approach
Tag FunctionHow a Tag Works
Processing FlowTLD Used to Describe the TagTag Handler Code DevelopmentHow a Tag is Used
Test CaseOutput of Test Case
166
Using Custom Tags with JSPs
Standard JSP ActionsuseBean, setProperty, getPropertyinclude, forward, plugin, params, param, fallback
Tags are Used to Develop and Invoke Custom ActionsTag Libraries are Collections of Custom TagsJSP Tags are Sometimes Referred to as “Actions”
Action is the “function” performed by a tag
84
167
Why Custom Tags?Role Based Development
Developers with various skillsets focus on the various MVC design pattern components
Keep Java out of JSPsUse custom tags to implement presentation logic (conditional processing, looping, etc.)Web designer/developer can focus on presentation
Keep Presentation out of ServletsJava Developers are not presentation experts
Best PracticeJSP custom tags used for presentation logic
168
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>
85
169
Custom Tags Creation and Use
Development PhaseTag/tag attributes designTag declaration in a TLDTag handler class developmentTag helper classes development
Use PhaseInclude tag library (taglib)Specify the attributesTest
170
Simplified Coding of Custom Tags
WSAD Page DesignerJSP->Insert Custom
86
171
Custom Tags Benefits
Makes JSP Development EasierWeb Developers can Focus on Presentation AspectPresentation Logic Becomes Reusable
172
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>
87
173
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>?
174
TLD Location
Implementing Classes in JAR fileTLD in META-INF Directory or SubDirectory
Implementing Classes in Web ApplicationTLD in WEB-INF Directory or SubDirectory
DTD Locationhttp://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd
88
175
Tag Handler Class
Code Implementing a TagImplements One of the Following Interfaces
Javax.servlet.jsp.TagJavax.servlet.jsp.tagext.IterationTag (extends Tag)Javax.servlet.jsp.tagext.BodyTag (extends IteratorTag)
Extends One of the Following ClassesJavax.servlet.jsp.tagext.TagSupport (implements IteratorTag)Javax.servlet.jsp.tagext.BodyTagSupport(extends TagSupport and implements BodyTag)
Tag Attributes handled with JavaBean-like setter methodsTag Handler Class Methods
doStartTag(), doAfterBody(), doEndTag()
176
Custom Tag Error Handling
Compilation ErrorsInvalid Tag formatMissing required attributes
Tag Handler JspExceptionInvalid values specified
89
177
Custom Tags Packaging
Place class files in a JARImport TLD into /WEB-INF/tldImport JAR into /WEB-INF/lib
178
Example: Custom Tags in WSAD
Put Tag Handler Classes in a Java ProjectAdd Java Project as a Project Utility Jar to the Enterprise Application
Update application deployment descriptorAdd Dependent JAR to the Java JAR Dependencies in the Properties of the Web ModuleCopy TLD to /WEB-INF/tld directory
90
179
Custom Tags ReviewAdvantages of Custom Tags
Makes JSPs easier to develop/test/maintainWeb developers can focus on the presentation aspectsPresentation logic becomes reusable
Custom Tag Development StepsTags and attributes designTLD construction/modificationTag handler class developmentJSP test
Attribute Values Processed in Tag Handler Class via JavaBean-Like Setter MethodsdoStartTag() Method is Associated with Tag Start ProcessingTaglig Directive Describes TLD Location and Specifies Tag Prefix
180
Part IX
Advanced Java Server Pages (JSPs)and Java Servlets
91
181
Objectives
Advanced JSPsSharing Data Between TagsIterating Tags
JSP Standard Tag Library (JSTL)Servlet Filters
182
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”/>
92
183
Example Tag
Producer: <ils:now id=“rightnow”
type=“com.ibm.ils.library.TimeBean”/>Consumer:
<jsp:getProperty name=“rightnow” property=“time”/>
184
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
93
185
getVariableInfo( ) MethodPublic VariableInfo[] getVariableInfo(TagData data)
TagData contains attribute/value information for a given tag instanceVariableInfo[] 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 objectClass name of the share objectBoolean indicating that object was created by this tagVariable scope (i.e., AT_BEGIN, AT_END, or NESTED)
i.e., Where the object will be declared in the generated servlet
186
TagExtraInfo Subclass Implementation Samplepackage 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;
}}
94
187
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>
188
Tag Implementation Sample
// package and imports not includedPublic class NowTag extends BodyTagSupport {
// Element attribute nameprivate 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
}}
95
189
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” />(…)
190
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
96
191
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>
192
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>
97
193
Iterating Tags Implementation MechanismFirst 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 BodyThird 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
194
Iterating Tag Implementation Steps
Add Tag to TLDAdd <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 ClassProvides information about the shared current element of the list to the container
Create Tag Handler Class IteratingTag
98
195
<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>
196
IteratingTagExtraInfo Subclass Implementation Samplepackage 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;
}}
99
197
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 nameprivate String id;private String classname;private Iterator iterator;
// constructor and setter methods setId(), setClassname() have been omitted(…)
198
(…)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 initializationint 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;
}(…)
IteratingTag Implementation Sample(continued)
100
199
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 againpageContext.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;
}(…)
200
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;
}(…)
101
201
IteratingTag Implementation Sample(continued)
(…)public void release {
id = null;classname = null;iterator = null;super.release();
}}
202
Java Server Pages Standard Tag Library
JSTL Specification is Part of JSR-052Core
Iteration <forEach>Conditional <if>, <choose>, <when>, <otherwise>Expression language
XML ProcessingParsing, XPath, XSL transformation (<x:transform>)
Data FormattingI18N capabilities for dates, currency, and numbers
RDBMSSQL support (<sql:query>, etc.)
102
203
Advanced JSP Tags Review
The TagExtraInfo Class Needs to be Extended to Provide Information about Shared Variables to the JSP ContainerThe Information Specified in the VariableInfo Object Includes:
Shared variable idShared variable class nameBoolean flag indicating if the object referenced by the variable was created by the tagVariable scope
Iterating Tags Extract Elements in a Collection and Make the Current Element of the List Available to Other Tags as a Shared VariableThe Tag Handler Class Typically Implements doStartTag() (loop initialization), doAfterBody() (loop increment), and doEndTag() (post-loop processing)
204
Servlet Filters
Introduced in the Servlet 2.3 API specificationReusable componentsUsed to transform the content of HTTP requests, responses and headersCan be configured into chains of multiple filtersIndirectly invoked by a client request to a Web resourceHandle request pre-processing, response post-processing, request/response transformation, control transfer, execution blocking
103
205
Sample Filter UsesAuthenticationLogging/AuditingImage ConversionData CompressionEncryptionTokenizingEvent TriggeringXSLTMIME-typeCaching
206
Filter Chains and Filter ImplementationFilters may be configured in a chainFilterChain object is used to describe the chainFilters are invoked via nested calls
Servlet container invokes doFilter() on 1st filterFirst filter invokes doFilter() on next filter, etc.
Servlet filtering also referred to as Servlet ChainingFilter implementation (Select File -> New -> Other -> Filter)
Filter class implements javax.servlet.FilterFilter class provides implementations for init(), doFilter(), and destroy() methodsFilter is described in the deployment descriptor with the <filter> elementFilter chaining configuration is described in the deployment descriptor with the <filter-mapping> element
104
207
Java Servlet API Interfaces
javax.servlet.Filterinit(), doFilter() (FilterChain object passed as parameter), destroy()
Javax.servlet.FilterConfigFilterConfig object passed by container to filter init()getFilterName(), getInitParameter(), getInitParameterNames(), getServletContext()
Javax.servlet.FilterChaindoFilter()
208
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
105
209
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)
210
Servlet Filters ReviewBuilding a Filter Requires the Implementation of the javax.servlet.Filter interfaceThe FilterChain Object Defines the Sequence of Filter ExecutionThe Container Passes and Object of Type FilterChain to the 1st FilterThe Execution Follows that in the Filter Mapping Elements in the Deployment Descriptor, and the Order is Determined by te Order of Matching Filter Mapping ElementsA Filter Can Control the Flow or Processing by note Calling the chain.doFilter() MethodThe Requested Web Resource is the Last on the Filter ChainTypical 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
106
211
Part X
Java Server Faces, and Related Frameworks
See: http://java.sun.com/j2ee/javaserverfaces/download.html
http://java.sun.com/j2ee/javaserverfaceshttp://java.sun.com/j2ee/javaserverfaces/docs/tutorial.html
212
Java Server Faces
Simplified Server-Side UI BuildingReusable UI component assemblyData source connectionsClient-Server event wiring
JavaServer Faces TechnologyAPIs (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
107
213
Java Server Faces Applications
Run in a Java Servlet Container like any Other Java Web ApplicationInclude traditional components:
Model objects (i.e., JavaBeans)Event ListenersPages (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 pageCustom tag library to represent event handlers, validators, etc.UI components are represented as stateful server objectsValidators, event handlers, and navigation handlers
214
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> </html>
108
215
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>
216
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>
109
217
Related Java Web FrameworksSun 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 levelCustom 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 FacesCan use JavaServer Faces component-level functionalities (e.g., rendering, events, etc.) within a pageCan 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:
Maverick, WebWork, Tapestry framework, etc.
218
Part XI
Conclusion
110
219
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 solutionsJBoss provides a resource and platform effective alternative to higher end J2EE application serversJBoss is an open source solution use by many small enterprises today
220
Readings
ReadingsBuilding J2EE Applications with IBM WebSphere:
Chapters 9-15, 17, 19-23Microsoft .Net Distributed Applications:
Sections on COM+ Services (continued)Handouts posted on the course web siteExplore J2EE environmentsRead related white papers/documentation on the J2EE environments
111
221
Project FrameworksProject 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 ASPSun One Active Server Pages 4.0
http://wwws.sun.com/software/chilisoft/index.htmlApache TomcatMacromedia JRun4Apache Cocoon 2/XSPVisibroker, OrbacusRMI-IIOPWebLogic 8.1, WebSphere 5.0, JBoss
222
Assignment
Assignment:Explore the textbooks’ references to Application Server technology (continued)#5 (continued): Due date is 11/05/01Session 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)
112
223
Next Session:J2EE Component-Based
Computing Environments (Part III)
Other J2EE Application ServersSunOne, Inprise, Sybase EAServer, etc.
Enterprise Component Development with J2EEDesigning J2EE Component-Based ArchitecturesOther J2EE Application Servers
top related