practical web application architectures using ibm websphere geoff hambrick ibm websphere enablement...
Post on 28-Dec-2015
230 Views
Preview:
TRANSCRIPT
Practical Web Application Architectures using IBM WebSphere
Geoff HambrickIBM WebSphere Enablement Team
Introduction
This session will include: an overview of IBM WebSphere Standard and Advanced runtime arc
hitectures– each will be treated separately
practical details about the programming model:– components a developer has to program, and how– the kinds of services that are available and how are they used– best practices, from both bottoms up and top down perspectives– discussion of scenarios that you will likely encounter
hands on examples illustrating various "design patterns" useful in developing web applications
Why IBM WebSphere?
Initial scenarios focused on Web Publishing world wide access to essentially static information not much distinction between clients can get by with read-only non-transactional services
Client
Kasparov
Internet
InternetWeb Server
Client
Why IBM WebSphere?
Rapidly evolving to personalized Web Applications tie customers, business partners and employees together using the Web need transactions, persistence and security under program control drive the need for a Web Application Server to provide these services and nece
ssary infrastructure
Bank Customer
Loan Officer
Web Application Server
Banking Data Center
(CICS, IMS, DB2, Oracle)
Internet
Intran
etInsurance Underwriter
Extranet
Why? IBM WebSphere Provides a Complete End to End Solution
Data centerExisting
Apps & DBs(CICS, IMS, DB
2, Oracle)
Multiple Business Server P
latforms(AIX, SUN. NT, MVS...)
1. Development PhaseMulti-author environme
ntlibrary system
Multi-disciplinary teamHTML, Java and c
ontentPublishing to web serve
r
3. Evaluation PhaseLink checkingSite mappingUsage patternsPerformance statisti
cs
Clustered ProductionWeb App Servers
StagingServer
DevelopmentServer
2. Production Phase Runtime environmentLoad balancingDirectory, Security
Web master
Web Team
IBM WebSphere Site Analysis Tools
IBM WebSphere Application Server
Performance Pack IBM Connector Seri
es
IBM WebSphere Studio
Workbench
NetObjects Fusion
ScriptBuilder
VA java
Standard Runtime Architecture:High level view
Web Server
WebSphere plug-in
Web Application Server Back-end
HTTP
Client
Assumes web applications consist of three logical tiers, but IBM WebSphere Standard only includes middle tier components
Client– typically is a Web browser that communicates to the Web Server using HTTP
Middle Tier– requests for static pages are handled directly by the WebServer (Standard includes IBM HTTP Server)– dynamic requests are passed to the Web Application Server (in or out process) through the WAS plug-in
Back End– repository of enterprise function and data– communication with client depends on technology
Standard Runtime Architecture:Inside the Web Application Server
Web Server
WebSphere plug-in
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAVA JAVA
JAVA
HTTP
Client
Servlet Services– standard Java APIs to handle HTTP requests from client
Application Components– standard artifacts programmed by Web Application developers using Java
Connectors (not included with IBM WebSphere Standard Edition)– Java APIs to handle access to back end resources
Java representations for each of the three logical tiers:
Standard Runtime Architecture:Web Application Components
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
HttpServlets– Java programs that control the application flow from page to page
Java Server Pages– extend HTML to alllow fill-in-the blanks from programmatic components
Java Beans (no special support provided by IBM WebSphere Runtime)– provide an extensible contract between other application components
Standard artifacts programmed by the developer for the middle tier, roughly one component for each logical tier
In general, Java servlets are an open standard for executing code on a server: get all the advantages of Java
– easy to code object model– platform independent
are called within the server process – have access to security and transaction context
remain resident once they are loaded for performance– service method handles one or more requests
are themselves stateless– servlets scale across clustered, multiprocessor, multithreaded envir
onments– have access to various Java standard services to maintain state
Web Application components:HTTP Servlets
Web Application components:HTTP Servlets (continued)
HTTP Servlets are a standard Java servlet subtype that: can be found in javax.servlet.http.* package installed into <IBMWEBAS>/servlets directory have methods to handle various lifecycle events and HTTP reques
ts – most common are doGet(), doPost(), doPut()– the service() method is overridden when the processing is the same
across request type – the init() and destroy() method can be used for one time startup and
shutdown logic can be used to explicitly generate a reply on behalf of the Web Ser
ver– HTML, MIME, XML, DHTML
however, are best used to encapsulate conditional application flow logic
– leave the presentation logic to Java Server Pages– encapsulate business logic in Java Beans, connectors
HttpServlets: A high-level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for an HttpServlet to the Web Server– web server uses its specific mapping rules and determines it should route request to the Web Sphere plug in– plug in activates a Web Application Server (in or out process)
Web Application Server activates HttpServlet with appropriate Servlet Services– Servlet accesses information from servlet services to determine what to do
HttpServlet generates the appropriate HTML reply back to WAS through the Servlet Services based on result– WAS routes reply back to plug in, which passes though to the Web Server specific APIs
Web Server routes reply back to the Browser for handling– action depends on the reply contents
1.
2.
3.
4.
Purpose: shows how an HttpServlet can be used to generate any and all dy
namic content– gets values from a number of sources (e.g. instance variables, sessi
on state) shows basic structure of an HttpServlet class
– implements service method anda private method to handle CHECKED radio button
– however, at this point we don't care too much about the details of the code
graphically illustrates why "monolithic" servlets have development/maintainability problems
– HTML is hidden in println statements and cannot be edited with WYSIWYG editors
– changing layout requires testing of application flow logic and vice versa
HTTP Servlets:HitCount1 example
HTTP Servlets:HitCount1 example (continued)
How to run it: put HitCount1.class in <IBMWEBAS>/servlets directory URL will be http://<yourWS>/servlet/HitCount1 try various radio buttons and hit Increment to "count up" and note
behaviors in various circumstances– servlet instance variable resets when WAS is brought down and is flak
y in concurrent user situations– session state (create if necessary) resets when all browsers on client a
re stopped or on session timeout– existing session state only will fail first time browser is started or on ti
meout– sum of active sessions also fails the first time or on timeout, but may
show a different count than session if: there are other clients using HitCount* with the session options you recycled your browser and "orphaned" a session state valu
e within the timeout period
HTTP Servlets:HitCount1 example (continued)
Statistics (a rough estimate of complexity): number of new components: 1 source (bytes): 6054
Things to try: change the logic, for example:
– default to no action (rather than "SRV")– synchronize increment of count to make code thread safe
change the layout:– remove "no cache" calls and check out behavior differences– add session count to sum of active sessions choice
in any case you will have to:– edit the HitCount1.java file (use WordPad)– compile it (javac HitCount1.java)– move HitCount1.class to <IBMWebAS>/servlets
Web Application components:Java Server Pages
What is it: provides a standard server side scripting language as extensions
to HTML– JavaSoft standard (with IBM "template" extensions that are being co
nsidered for inclusion)– JSP files are deployed into webserver's HTML directory– WAS plug-in automatically "compiles" them into HttpServlets
best used when the content is mostly static, with some fill-in-the-blanks
– can be edited using WYSIWYG tools– should be treated as a "view" component with no control logic
can be used to replace explicitly coded HttpServlets to eliminate compile step, however:
– no longer easily edited by a WYSIWYG tool– should be treated as a "controller" component with no display logic
Web Application components:Java Server Pages (continued)
Most common tags: set up a JavaBean to be used later using <%=beanname.property%> tags
– can be created or not, and scoped to a request, session or user profile– <BEAN name="name in scope" varname="name above" type="class || interface nam
e"– create="yes || no" beanName="class or .ser file name"– introspect="yes || no" scope="request || session || userprofile" >– <param "propertyname"="value to set after instantiation" ... >– </BEAN>
set a value or declare method to be substituted later using <%=variable> tags– <SCRIPT> runat=server>– String variable = code to set the value;– </SCRIPT>
to insert some java code that will directly generate output use <% ... %>, but mainly for:
– "controller" JSPs (that call another JSP for layout)– read only data access code– dynamic tables and lists, or tags (like CHECKED or SELECTED) that can only
appear on one item
Servlet Services
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
Java Server Pages: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for a JSP to the Web Server Web Application Server compiles the JSP into an HttpServlet and invokes it JSP generates HTML reply back to Web Server Web Server routes reply back to the Browser for handling as before
1.
3.
4.
2.
Purpose: shows how to use a JSP in place of an HttpServlet
– control logic is embedded in <% %> tags– JSP must now read values from request in <%= %>
illustrates similar problems with monolithic programs– still must test both logic and layout if either one changes– cannot use WYSIWYG tools to edit layout– cannot use IDE tools to edit logic
How to run it: put HitCount2a.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount2a.jsp Functionally, there is no difference However:
– no need for an explicit compile step– performance is slower (a lot on first call)
Statistics: number of new components: 1 source code (bytes): 4307 difference with HttpServlet is due to elimination of lots of Java syntax
Java Server Pages: HitCount2a example
HttpServlets plus Java Server Pages: A high-level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for an HttpServlet to the Web Server (as before) Web Application Server activates HttpServlet with appropriate Servlet Services
– Servlet accesses information from servlet services and connectors to determine which JSP to call HttpServlet activates the appropriate JSP with appropriate services
– details to be discussed later JSP accesses information from servlet services to generate HTML reply back to Web Server Web Server routes reply back to the Browser for handling as before
1.
2.
4.
5.
3.
Purpose: shows how a Servlet can be used with JSPs to generate dynamic content
– eliminates all the layout code from the servlet – sets string value for count message and source into HttpServletRequest
shows basic structure of a JSP– mostly HTML tags– use of <SCRIPT> tag to implement method to handle CHECKED radio buttons– use of <% %> tag to insert code to prevent caching of result and get attribute valu
es from request– use of <%= %> tags to compute CHECKED attribute on radio buttons and insert c
ount message graphically illustrates how this MV architecture is easier to develop and maint
ain– HTML is in a separate file and can be edited with WYSIWYG editors– layout can be is independent of application flow logic and vice versa
however, shows the "looseness" of the contract between the HttpServlet and JSP
– need something to document request attribute name/value semantics– not toolable, so cannot use drag and drop tools to generate <% %> and <%= %>
HttpServlets plus Java Server Pages:HitCount2 example
HttpServlets plus Java Server Pages:HitCount2 example (continued)
How to run it: put HitCount2.class in <IBMWEBAS>/servlets directory put HitCount2.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount2.jsp starts with an empty page, but then behaves exactly like HitCount1
Statistics: number of new components: 2 (HttpServlet, JSP) source code (bytes): 5857 (4643, 1214) has 97 fewer bytes of total source code than HitCount1 due to elimination of
println related logic Things to try:
change just the logic in HitCount2.java – follow steps from HitCount1
change just the layout in HitCount2.jsp – simply edit the .jsp in <WebServer>/<HTML>
change the "contract" between them by adding a new variable to display
Web Application components:Java Beans
JavaSoft's "self descriptive, toolable" object standard provide a means to encapsulate functions and data tools and programs can query JavaBean about available methods and properties
Java Beans can be "externalized" and "internalized" (serialized) to and from a .ser file provides a degree of single instance persistence and configurability controlled by program in which Bean is instantiated
Typical applications: Applet Presentation classes (e.g. tables, dialogs)
– not discussed here Common data access classes (e.g. database queries)
– will see an example of this later Contracts between components (e.g. HttpServlets and JSPs)
– basically a "pass by value" data structure
HttpServlets + JSPs + JavaBeans: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for an HttpServlet to the Web Server (as before) Web Application Server activates HttpServlet with appropriate Servlet Services (as before) HttpServlet creates and loads a JavaBean with the results HttpServlet activates the appropriate JSP with a reference to the JavaBean JSP requests result information from Java Bean Java Bean returns values back to JSP JSP generates HTML reply back to Web Server, filling in the blanks with the values requested Web Server routes reply back to the Browser for handling as before
1.
2.
7.
8.
4. 3.
5.
6.
Purpose: shows how a Servlet can be used with JSPs to generate dynamic
content using a JavaBean contract– HttpServlet news up JavaBean, sets its attributes, then adds it into t
he request attributes– JSP uses <Bean> tag instead of <% %> to get values for <%= %> tag
s– JavaBean encapsulates attribute values and checked method to han
dle conditional logic illustrates need for extensions to JSP
– need <NO_CACHE> tag to replace "shotgun" approach– possibly others, like for radio buttons to simplify logic to handle "CH
ECKED" attribute
HttpServlets + JSPs + Java Beans:HitCount3 example
HttpServlets + JSPs + Java Beans:HitCount3 example (continued)
How to run it: put HitCount3.class and HitCountBean.class in <IBMWEBAS>/servlets direct
ory put HitCount3.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount3.jsp
Statistics: number of new components: 3 (HttpServlet, JSP, JavaBean) source code (bytes): 6129 (4718, 942, and 469, respectively) HttpServlet is 75 bytes larger than HitCount2 due to overhead of creating Bea
n and setting values JSP is 272 bytes smaller and much less complex due to elimination of:
– <SCRIPT> tag to define checked method (resides in JavaBean)– code to get request attributes (replaced by <Bean> tag)
overall application is 272 bytes larger (coincidentally), however:– the JavaBean source code serves as project documentation (can use javadoc)– can use JavaBean wizards (like those in IBM WebSphere Studio) to code with it– the previous application did not consider this complexity at all...
HttpServletRequest– provides access to URL parameters, session state, and the session context
HttpServletResponse – provides methods to control and generate the reply or invoke other application components
HttpSession– used to maintain user session data between requests (can be clustered)
HttpSessionContext– enables coordination between multiple user sessions
Standard Runtime Architecture:Servlet Services
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Represents the client tier within the Web Application Server– part of the javax.servlet.http.* package
Servlet Services:HttpServletRequest
What is it: encapsulates WebServer API differences related to getting request data reference is obtained from service() and do<XXX>() methods
Most commonly used functions: determine what parameters can be found in the URL (if any)
– String[] names = request.getParameterNames(); parse parameters from the request URL
– String[] values = request.getParameterValues("name");– values is null if the named parameter is not found
get an existing user session associated with this request (if any)– HttpSession session = request.getSession(false);– will only return session state if it already exists
get an existing user session, or create it if necessary– HttpSession session = request.getSession(true);
set new values to pass to "chained" servlets (including Java Server Pages)– this is how request specific JavaBeans are passed to JSPs– ((com.sun.server.http.HttpServiceRequest)request).setAttribute("name", value);
get an attribute passed from a chaining HttpServlet– <Type> value = (<Type>)request.getAttribute("name");– value is null if attribute does not exist
Servlet Services:HttpSession
What is it: a standard interface to maintain user session (conversational) information
– required because HTTP is a "stateless" protocol– data is stored on the server and mapped to user through a session ID– our implementation works with a cluster of Web Application Servers
reference is obtained from either:– the HttpRequest (for the one associated with the request)– the HttpSessionContext (given a specific session id)
trades quality of service for ease of use– cannot count on persistence of session data
can time out do not use as a "poor man's" database
– best to use for easily recomputable values, such as: login tokens references to objects that are expensive to obtain
– values must be serializable to allow the data to be: passed among servers in a cluster cached in and out of memory
Servlet Services:HttpSession (continued)
Most commonly used functions: set an application specific value
– session.putValue("name", value);– value must be a serializable Object for clustering and persistence to work
get an application specific value set previously– <Type> value = (<Type>)session.getValue("name");– value is null if the name does not exist in the session
get the session id– often used to provide cross linking between sessions in "collaborative”
applications– String sessionId = session.getId();
get the session context– used to locate other user sessions in collaborative applications– HttpSessionContext context = session.getSessionContext();
"kill" the session (can trigger HttpSessionBindingListener event) – session.invalidate(); // remember: sessions are associated with the user, not an individ
ual HttpServlet– session.removeValue("name"); // removes just the values desired, rather than
whole session
Servlet Services:HttpSessionContext
What is it: provides a standard interface to coordinate multiple sessions for example:
– on line auctions– multi-player games (checkers, bridge)– same user across multiple machines (or browser instances that do
n't share cookies) reference is obtained from an HttpSession like sessions, using HTTPSessionContext trades off quality of ser
vice, especially security, for ease of use– beware of inadvertently affecting other application session data (all i
s accessible)– probably best to use directory, database or EJB instead
Servlet Services:HttpSessionContext (continued)
Most commonly used functions get a specific user session:
– HttpSession session = context.getSession("session Id");– session returned is null if the session id is not found
iterate through the sessions in a context:– Enumeration ids = context.getIds();– while (ids.hasMoreElements()) {– String id = (String) ids.nextElement();– HttpSession session = context.getSession(id); – // Operate on the session returned (may be null)– }
Servlet Services:HttpServletResponse (continued)
What is it: encapsulates WebServer API differences related to generating the res
ponse to an HTTP request reference is obtained from service() and do<XXX>() methods
Functions that can be ignored if using MVC architecture: to write HTML sent to the browser in response to the request
– should mainly be used within a Java Server Page, if explicitly at all (see HitCount1 vs. HitCount2)
– PrintWriter pw = response.getWriter(); // retrieves object into which HTML can be written
– pw.print(<HTML string>); or pw.println(<HTML string>);– pw.flush() // optional, to insure block of data is written
to set the header to avoid caching of dynamic pages instead of <Meta> tags
– should mainly be used within a Java Server Page– response.setHeader("Pragma", "No-cache");– response.setHeader("Cache-Control", "no-cache");– response.setDateHeader("Expires",0);
Servlet Services:HttpServletResponse (continued)
Functions needed if using MVC architecture: to directly invoke a Java Server Page from an HttpServlet
(or another JSP)– this is the best performing method for generating HTML from within "rea
d only" HttpServlets– downside is that browser redisplay functions (e.g. back, forward,
resize, reload) re-execute servlet when caching is disabled using the above technique
– see HitCount2 and HitCount3 for an example– ((com.sun.server.http.HttpServiceResponse)response).callpage(– <JSP URL>, <HttpRequest>– );
to redirect to another URL– done so that redisplay does not cause update HttpServlets to be execute
d over and over– response.sendRedirect(<url + query string>);
Servlet Services
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
Servlet-JSP redirect using URL only: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for an HttpServlet to the Web Server as before Web Application Server activates HttpServlet with appropriate Servlet Services as before HttpServlet invokes a sendRedirect with the JSP after setting attributes into URL Web Server sends URL redirection for JSP back to Client Browser receives the redirection and sends an HTTP request for the JSP directly WAS activates the JSP with attributes in the request JSP generates HTML reply back to Web Server, filling in the blanks with the values requested Web Server routes reply back to the Browser for handling as before
1.
2.
7.
4.
5.
3.
6.8.
Purpose: shows how to use URL redirection when selected from page
– display values must be appended to URL (requires string conversion)– JSP must now read values from request in <%= %>
also shows how cache disabling code can sometimes be eliminated in JSP– we can treat the JSP like a static page once it formats the results
How to run it: put HitCount4.class in <IBMWEBAS>/servlets directory put HitCount4.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount4.jsp Check differences with previous examples
– Increment button is the only event that causes a "hit" on the HttpServlet– performance is a little slower when the HttpServlet is hit– however, redisplay is faster unless cache is cleared (no traffic at all!)– even then, the JSP is directly invoked, eliminating the first round trip (flows 1-4)
Statistics: number of new components: 2 (HttpServlet, JSP) source code (bytes): 5729 (4653, 1076) comparison with previous example is not as important (different behavior)
Servlet-JSP redirect using URL only: HitCount4 example
Servlet-JSP redirect using JavaBeans: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet
JavaServer Page
Java Bean
Web Application Server
ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Browser sends HTTP request for an HttpServlet to the Web Server as before Web Application Server activates HttpServlet with appropriate Servlet Services as before HttpServlet creates and loads a JavaBean with the results as before HttpServlet invokes a sendRedirect with the JSP after setting JavaBean into session state WebServer routes URL for JSP back to Client Browser intercepts the reply and sends an HTTP request for the JSP directly WAS activates the JSP with the Java Bean reference in session state JSP requests result information from the Java Bean Java Bean returns values back to JSP JSP generates HTML reply back to Web Server, filling in the blanks with the values requested Web Server routes reply back to the Browser for handling as before
1.
2.
10.
5.
3.
8.
9.
6.
4.
7.11.
Servlet Services
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
Purpose: shows how to use URL redirection with a Java Bean
– display values must be set into a Bean– Bean must be set into session state– JSP must use Bean tag scoped to session state
shows first example of JavaBean reuse!– HitCount3Bean can be used as is...
How to run it: put HitCount5.class in <IBMWEBAS>/servlets directory (HitCount3Bean.class
should be there already) put HitCount5.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount5.jsp select URL redirection and check differences with HitCount4
– URL line on browser has no parameters displayed– use of session state may have performance implications in a cluster under load– when session state expires, "defaults" are displayed if reload is forced
Statistics: number of new components: 2 (HttpServlet, JSP)
– Java Bean doesn't count as it is reused source code (bytes): 5693 (4902, 791)
Servlet-JSP redirect using JavaBeans:Hands on example (HitCount5)
Standard Runtime Architecture:Connectors
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
A variety of Java APIs over connections to back end resources (not included with Standard Edition)
Java Data Base Connectivity (JDBC) over UDB– based on a JavaSoft standard– provides for dynamic SQL queries into relational database backed up by DB2 Universal DataBase
Others– in a nutshell, HTTPServlets and JavaBeans are excellent clients anywhere there are Java APIs provided– CICS, MQ, IMS, ComponentBroker, SanFransisco, CORBA ORBs, ...– just make sure to include the appropriate packages in the CLASSPATH (in bootstrap properties)
Connector APIs:Java Data Base Connectivity
What is it: provides a standard interface to execute dynamic relational database queries
is part of javax.sql.* package the current implementation is based on DB2 Universal Database
can use other databases with appropriate driver
Connector APIs:JDBC (continued)
Most commonly used functions: obtain a connection to the database (consider using connection manager)
use a "class" method (often handled in HttpServlet init() method) Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); // only need be done once Connection con = DriverManager.getConnection("database URL"); // once per connect
ion create an object through which to execute one or more SQL statements
Statement stmt = con.createStatement(); should close() statement when done
execute a command that is not expected to return a result e.g. "insert" and "update" do not forget to "commit" changes stmt.executeQuery("statement");
execute a query that is expected to return a result e.g. "select" statements ResultSet result = stmt.executeQuery("statement"); while (result.next()) {
<Type> value = (<Type> )result.getObject(<item# in query select clause>);// Operate on this or other values as desired}
HttpServlet-JDBC: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Web Server makes a request for an HttpServlet as before Web Application server invokes the HttpServlet as before HttpServlet directly accesses JDBC using connection and statement object JDBC implementation sends SQL calls to DB2 UDB DB2 UDB sends the result back to the JDBC client JDBC implementation converts the results into Java variables and returns them to the Http
Servlet - ?. HttpServlet uses one of the previous techniques for generating HTML
– directly embedded in the HttpServlet code– JSP from request attributes or a bean, using URL redirection or callpage
1.
2. 3. 4.
5.6.
Purpose: shows how to use JDBC within a Servlet
– adds button to JSP– adds code to HTTPServlet (connection made in init method)
everything else is the same as HitCount5– reuses HitCountBean3 again in redirect call
How to run it: put HitCount6.class in <IBMWEBAS>/servlets directory
– HitCount3Bean.class should be there already put HitCount6.jsp in <WebServer>/<HTML> directory must have DB2 UDB 5.0 or better with samples installed
– create table HITCOUNT (primaryKey varchar(251) not null primary key, theValue Integer) URL will be http://<yourWS>/HitCount6.jsp select database source and check behavior
– counts up regardless of whether WAS or Browser recycles– shows error if database goes down– see what happens if you directly modify the database table using DB2 CLP
Statistics: number of new components: 2 (HttpServlet, JSP) source code (bytes): 7514 (6630, 884) comparison with HitCount5 shows an additional 1821 bytes (1728, 93)
HttpServlet-JDBC: HitCount6 example
HttpServlet-JDBC though a JavaBean: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Web Server makes request to Web Server as before Web Application server invokes the HttpServlet as before HttpServlet instantiates JavaBean and invokes access methods JavaBean accesses JDBC using connection and statement objects as appropriate JDBC implementation invokes SQL on UDB as before UDB sends result as before JDBC converts reply to Java as before (except JavaBean is requestor) JavaBean returns method result to HTTP Servlet - ?. HttpServlet generates HTTP response as before
1.
2.
4.
5.
6.
7.
3.8.
Purpose: shows how to wrap JDBC calls with a JavaBean
– replaces "gorpy" JDBC code in HttpServlet code with "cleaner" JavaBean access– JSP is basically the same (calls HitCount7 instead of HitCount6)
behavior is essentially the same as HitCount6– reuses HitCountBean3 again
How to run it: put HitCount7.class and HitCount7Bean.class in <IBMWEBAS>/servlets
directory put HitCount7.jsp in <WebServer>/<HTML> directory DB2 UDB should be set up as per HitCount6 instructions URL will be http://<yourWS>/HitCount7.jsp select database source and check that behavior is no different
from HitCount6– use them simultaneously and see what happens
Statistics: number of new components: 3 (HttpServlet, JSP, JavaBean) source code (bytes): 7653 (5182, 884, 1587) trading complexity (another bean) for reuse and a simpler,
stable HttpServlet– can replace the JDBC access with that to another connector by modifying
the bean changes the behavior without changing the servlet
– full Model-View-Controller separation!
HttpServlet-JDBC through a JavaBean:HitCount7 example
JSP-JDBC though a JavaBean: A high level end-to-end flow
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Web Server makes request to Web Server for a JSP as before Web Application server invokes the JSP as before JSP instantiates JavaBean and invokes access methods as part of <%= %> tag JavaBean accesses JDBC using connection and statement objects as before JDBC implementation invokes SQL on UDB as before UDB sends result as before JDBC converts reply to Java as before (except JavaBean is requestor) JavaBean returns method result to JSP JSP generates HTML to return to WebServer Web Server returns HTTP reply to Client browser as before
1.
2. 4.
5.
6.
7.
3.
8.9.
10.
Purpose: shows reuse of a data access JavaBean in a completely new "application"
– this one does not test all the features of Standard, and just shows counting the value
also shows how a JSP can be used without ever accessing an HTTPServlet– replaces URL to HttpServlet in FORM action with that of this JSP
How to run it: HitCount7Bean.class should be in <IBMWEBAS>/servlets directory already DB2 UDB should be set up from HitCount6 or HitCount7 put HitCount8.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount8.jsp Press increment button and watch count
– use it from several clients and HitCount6-7 sequentially and simultaneously to see what happens
Statistics: number of new components: 1 (JSP) source code (bytes): 479 (only does one function)
JSP-JDBC using a JavaBean:HitCount8 example
Some best practices to consider:Programming model perspective
Web Application Architecture use HttpServlets as as controller code that handles application flow logic
– may want to use specialized JSP to eliminate compile step– in any event, no layout code
use Java Server Pages to handle layout logic– may use a JavaBean that directly accesses back end data– however, include no application flow logic
Servlet Services HTTP request
– using a JavaBean to pass more than one attribute value in chained requests HTTP sessions
– use to hold recomputable values rather than application data– minimize the size by storing "keys" to data stored in other sources– choose session state variable names to insure uniqueness across server – take care not to wipe out session data for other applications– best technique is to use (reuse) a single JavaBean named for the HttpServlet
Connectors wrap calls with a Java Bean do as much as possible in HttpServlet init method use connection pooling techniques if not done transparently by connector
Some best practices to consider:Development role perspective
Role
Concern
ProgrammingSkills Required
Components Produced
Page Producer
Page Layout and Content
(View)
Application Assembler
Application Flow (Cont
roller)
Bean Builder
Business Logic (Model)
Web Master
Operational Environment (Application)
Java Server Pages, HTML, MIME types
HTTP Servlets, JavaBeans Java Bean
s
Configuration Data, Site Usage Statistics
Little or None
Pure Java Non
e
Java + others
Tools WYSIWYG Editors
Java IDE AdminSpecialized
Wizards
Components Used
JavaBeans
Java Beans+ others
AllJavaBeans
"Let the right expert do the work."
Some best practices to consider:A top down design perspective
Analyze business processes to be web enabled state-transition modelling captures functional requirements
– states capture information that is available– transitions capture events, conditions and actions that cause state changes
role analysis captures security requirements– information and transitions accessible by role– easiest if "granularity" is by state
Example "on-line mall" business process:
Entry
Fulfillment
Completed
submit
final shipment
ProductsProduct IDDescriptionPrice, shipping, ...
Order (status = tentative):Customer:
Name, address, etcMethod of Payment
Line Items:Product ID & quanti
ty
initiate
partial shipment purge
condition:credit check (order.total cost) is OK
action:order.status = confirmed
add/delete/changeline item
cancelCustomer
Shipping
Marketing
Some best practices to consider:A top down design perspective
Develop Web Application UI Architecture add "usability" states/transitions to analysis model:
– role & task based "home pages"– confirmation and error dialogs– may break large data entry screens into multiple pages
from the client (browser) perspective:– states are HTML "pages" (framesets, forms, tables, ...)– transitions are triggered by URL "links" (buttons, HREFs, ...)
Example Order Entry UI Architecture:
EditOrder Confirm
Submit
submit
ok
add
postproduct id &
quantity
cancel
back
OrderStatus
ConfirmCancel
back
LoginCustomer
close
edit
login
post customer info
changesok
Product Details
next set of products
back
showproduct details
Invalid Login
backinvalidok
valid payment
invalid paymentmethod
Some best practices to consider:A top down design perspective
Apply "design patterns" to determine server side components variations based on the Model-View-Controller paradigm:
– any "dynamic" content suggests a JSP to display the view; otherwise "pure" HTML
JSPs will likely have associated JavaBean(s) representing the underlying business model (driven out during analysis)
access should be read-only– any "dynamic" transitions (those with conditions or side effects) sugges
ts an HttpServlet to control them; otherwise "direct" links each dynamic transition should be represented by a single method
call on some object (will facilitate evolution) callPage() can allow inadvertent servlet execution, but never require
s use of session state (can use request attributes) sendRedirect() requires data in session state or query string
can be indicated graphically on the UI model (the "MVC baseball"):
JSP & Servlet
JSPonly
HTML & Servlet
HTMLonly
directlink
dynamicredirect
dynamiccallpage
Some best practices to consider:A top down design perspective
Example Order Application High Level Design:
submit
ok
add
postproduct id &
quantity
cancel
back
back
close
edit
login
post customer info
changesok
next set of products
back
showproduct details
Invalid Login
backinvalidok
valid payment
invalid paymentmethod
JSP & Servlet
JSPonly
HTML & Servlet
HTMLonly
directlink
dynamicredirect
dynamiccallpage
Login Customer
ConfirmSubmit
OrderStatus
ConfirmCancel
ProductDetails
EditOrder
KEY:
IBM WebSphere Standard Edition:Summary of features
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA
HTTP
Client
Everything you need to program and serve up dynamic content to the Web
IBM HTTP WebServer– can be used where customer does not have a preference
WebSphere plug in– enables use of WebSphere with NetScape, IIS, Apache, ...
Servlet Services– full implementations of standard APIs required to gain access to client information
Application Components– Java runtime supports execution of HttpServlets and JSPs that use Java APIs and JavaBeans
IBM WebSphere Standard Edition:Advantages and disadvantages
Web Server
WebSphere plug-in
HTTP Servlet Response
HTTP Servlet Request
HTTP Session Context
HTTP Session
HTTP Servlet
JavaServer Page
Java Bean
JDBC
CICS Java Gateway
MQ Connector
...
DB2 UDB
CICS
MQSeries
...
Web Application Server
Servlet Services ConnectorsApplication Components
JAVA
Back-end
JAV
A
JAV
A
JAVAJAVA JAVA
JAVA ???
???
???
HTTP
Client
Advantages– can exploit a "thin" (zero maintenance) client that only needs communicate using HTTP– standard set of Java components and services make programs easier to code and highly portable– more and more back end servers have Java clients available
Disadvantages– lots of different protocol stacks add unnecessary "thickness" to middle tier (client to back end)
connector's client code needs to be explicitly installed – without a standard set of connectors, ease of development and portability suffer
IBM WebSphere Advanced focuses on Client-Server with distributed objects and standard services
???
Client Server
Advanced Runtime Architecture:Client-server view
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
Standalone Java Application
JavaApplet
Servers
DB2 Universal Data Base
MQ Series
CICS
...
Back-end
Includes the "clients" we have seen before– HttpServlets, JavaBeans, JSPs
Also includes Standalone Java Applications and Java Applets as clients, however:– not explicitly supported in IBM WebSphere Advanced
Back end services are the same as before, however:– the goal is to simplify and standardize access to them– Enterprise Java Beans is the emerging standard for distributed object services– Internet Inter ORB Protocol (IIOP) is the emerging standard on-the-wire transport protocol
EJB Client APIs
IIOP
IIOP
IIOP
IIOP
Enterprise Java Beans
What is it: provides a standard framework within which to use distributable, transactio
nable, persistable, securable objects– is part of javax.ejb.* package
facilitates separation of interface on client and implementation on server– EJB developer packages various client interfaces– works together with JNDI and JTS
an EJB is actually a collection of related components packaged together into JAR file
– developer creates a "deployable" jar file: <IBMWEBAS>/deployableEJBs/<Bean>.jar
– at configuration time, it is "deployed" into another jar file: <IBMWEBAS>/lib/deployedEJBs/<Bean>.jar
quality of service depends on the container in which it is deployed– defers the decisions– makes coding simpler
"client" neutral– C, C++, any CORBA mappable language– Java applications, applets, Java Beans, HttpServlets, JSPs, Enterprise Java Bea
n implementations
Advanced Runtime Architecture:EJB Client API overview
Standalone Java Application
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
JavaApplet
JNDIContext
JTSUser Transaction
EJB Client APIs
EJBKey
EJBHome
EJBRemote Interface
JAVA
JAVA
JAVA
JAVA
JAVA
JAVA IIOP
IIOP
IIOP
Servers
DB2 Universal Data Base
IIOP
MQ Series
CICS
...
Back-end
Java Naming and Directory Interface– JNDI Context represents a node in the directory into which you can bind and lookup name value pairs
Java Transaction Service– JTS User Transaction represents the state of a unit of work, which can be begun, committed or rolled back by client
EJB specific classes and interfaces– EJB Home interface encapsulates methods used to create or find (for entities)– EJB Key class encapsulates data and methods associated with complex keys used to create and find entities– EJB Remote interface describes methods available to EJB client on a given instance of an entity or session bean
Enterprise Java Bean APIs:Java Naming and Directory Interface
What is it: provides a standard interface to bind "global" names to values
– is part of javax.naming.* package the current implementation is based on CORBA Naming Service
– provides for distributed objects, such as Enterprise Java Beans
Java Naming and Directory Interface (continued)
Most commonly used functions: obtain a top level directory from which to search
– use a "class" method (usually handled in HttpServlet init() method)– HashTable env = new HashTable(5); // tells class method which naming service t
o initialize– env.put(
"java.naming.factory.initial", "com.ibm.jndi.CosNaming.CNInitialContextFactory"
– );– Context initCtx = new InitialContext(env);
find an existing name in the directory:– org.omg.CORBA.Object o = (org.omg.CORBA.Object) initCtx.lookup("name");– can get a "name not found" exception– <Type> value = <Type>Helper.narrow(o); // "safe" CORBA cast
associate a new name to a value (the name cannot exist in the directory)– for now, the name must be a CORBA object– initCtx.bind("name", value); – be prepared to handle a "Name already exists" exception
associate a name to a value (whether it exists or not)– initCtx.rebind("name", value);
Enterprise Java Bean APIs:Java Transaction Service
What is it: provides a standard interface to control transactional behavior across multi
ple resources– is part of javax.jts.* package
the current implementation is based on the CORBA transaction service and only works with EJBs
– part of the org.omg.CosTransactions.* package– also need com.ibm.ejs.client.* package
Most commonly used functions (if used at all): to obtain a transactional control object
– org.omg.CosTransactions.Current tx = EJClient.getCurrent();– can get javax.jts.UserTransaction from an EJB context (to be discussed later)
to start a transaction– tx.begin(); // same whether a UserTransaction or Cos Current
to commit a transaction (fails if not in the context of a transaction)– tx.commit(); // for a UserTransaction– tx.commit(<boolean to indicate report heuristics or not>); // for Cos Current
to register that the transaction should rollback when commit is attempted– tx.setRollbackOnly(); // with wrappered UserTransaction– tx.rollback_only(); // for Cos Current
to roll back the transaction (fails if not in the context of a transaction)– tx.rollback(); // same whether a UserTransaction or Cos Current
Enterprise Java Bean Client model:Bean types
Sessions have no persistent identity usually created each time one is used and are relatively short live
d makes them very scalable
Entities have a persistent identity where each is created only once found afterwards (by key or query) deleted only at the end of their logical lifecycle
Enterprise Java Beans Client model:Components
EJB interface provided by Bean Builder role defines the methods that can be executed on a bean by the client program
EJB Home interface provided by Bean Builder role defines methods by which associated EJBs are created, found and queried is linked to a container in the Enterprise Java Server
EJB Key class provided by Bean Builder role for Entity Beans with specialized keys holds the state needed to uniquely identify an entity bean must be serializable, have a hash value and an equals() method
EJB HomeHelper class generated by CORBA and EJB packaging tools used to safely cast a generic CORBA object reference to a Home interface supports the narrow() method (can use javax.rmi.PortableRemoteObject)
Standalone Java Application
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
JavaApplet
EJBKey
JNDIContext
JTSUser Transaction
EJB Client APIs
EJBHome
EJBRemote Interface
JAVA
JAVA
JAVA
JAVA
JAVA
JAVA
EJB Client Impls
EJBRemote
Stub
JNDIContext
Stub
CORBA Object
JAV
A
EJB HomeStub
IIOP
IIOP
IIOP
Servers
DB2 Universal Data Base
IIOP
MQ Series
CICS
...
Back-end
JAVAEJB
Home Helper
Lookup home through JNDI Context (1-7) Start transaction (8-9, optional, and not necessarily good practice) Narrow CORBA Object to Home (10-16) Create a Key (17-18, optional) Create or lookup EJB through Home (19-24) Execute methods on EJB remote interface (25-30)
1. 2. 3.
4.6.7.8.
9.10. 11. 12.
13151617.
18.19.
24.
20.
23
21.
22
Advanced Runtime Architecture:Client side end-to-end flow
25.
30.
26.
29
27.
28
5.
14
Purpose: shows use of an EJB shows some techniques for holding on to the reference
How to run it: HitCount.class should be in <IBMWEBAS>/servlets directory alr
eady (from advanced install) DB2 UDB should be set up from HitCount6 or HitCount7 put HitCount.jsp in <WebServer>/<HTML> directory URL will be http://<yourWS>/HitCount.jsp Press increment button after selecting EJB and various transa
ction options and watch count– use it from several clients and HitCount6-7 sequentially and simu
ltaneously to see what happens Statistics:
number of new components: source code (bytes):
HttpServlet using an EJB:Hands on example (HitCount)
Advanced Runtime Architecture:Server side view
Standalone Java Application
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
JavaApplet
EJBKey
JNDIContext
JTSUser Transaction
EJB Client APIs
EJBHome
EJBRemote Interface
JAVA
JAVA
JAVA
JAVA
JAVA
JAVA
CORBA Object
EJB Client Impls
EJBRemote
Stub
JNDIContext
Stub
JAV
A
EJB HomeStub
Location Service Daemon
Persistent Name Service
IIOP
IIOP
IIOP
IIOPEJBImpl
Enterprise Java Server
Servers
EJBHome Helper
JAVAIIO
P
DB2 Universal Data Base
IIOP
MQ Series
CICS
...
Back-end
Location Service Daemon (LSD):– registry for CORBA services– PNS and EJS are both registered
Persistent Name service (PNS)– implementation of CORBA name service– used to locate EJB Homes
Enterprise Java Server (EJS)– hosts implementations of EJB instances and homes– CORBA skeletons for Home, implementation and container
CORBA Naming Skel-Impl
Advanced Runtime Architecture:Inside the EJS (n-tiers)
Standalone Java Application
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
JavaApplet
EJBKey
JNDIContext
JTSUser Transaction
EJB Client APIs
EJBHome
EJBRemote Interface
JAVA
JAVA
JAVA
JAVA
JAVA
JAVA
CORBA Object
EJB Client Impls
EJBRemote
Stub
JNDIContext
Stub
JAV
A
EJB HomeStub
CORBA Naming Skel-Impl
Location Service Daemon
Persistent Name Service
IIOP
IIOP
IIOP
IIOP
Enterprise Java Server
EJBImpl
Servers
EJBHome Helper
JAVA
EJBHome
Skel-ImplJAVA
EJBRemote Skeleton
JAVA
JNDI Context
JNDI Context StubIIOP
Container Impl
JAV
A
JDBC
IIOP
DB2 Universal Data Base
IIOP
MQ Series
CICS
...
Back-end
JNDI Context and associated Stub– Container implementation and EJS use JNDI to bind Homes according to name in deployment descriptor
Container Implementation– maps EJB implementations to underlying persistence mechanisms (if any)
EJB Home Skeleton-Implementation– demarshals IIOP methods and delegates them to Container as appropriate
EJB Remote Skeleton– demarshals IIOP methods and delegates them to EJB implementation as appropriate
EJB Implementation– implements methods of EJB (can use other EJBs and connectors as necessary, making an n-tier model)
EJB Implementation model:Components developed by Bean Builder
<Bean>, <Bean>Home and <Bean>Key see application assembler components implemented by bean builder for use by client
<Bean>Bean implements javax.ejb.* interfaces depending on the bean type provides implementation of <Bean> interface methods
<Bean>FinderHelper (associated with IBM DB2 container) aids in generating find and query methods declares static strings associated with find methods on Home string defines associates SQL 'where clause' used to find data
<Bean>DeploymentDescriptor describes characteristics of the bean implementation enables quality of service to be decided at deployment, not develo
pment
EJB implementation model:Bean types
Session Beans stateless sessions simple stateful sessions transactional stateful sessions
Entity Beans self managed entities container managed entities
Enterprise Java Bean implementationStateless session beans
Considerations: used for task oriented objects where:
– all parameters required are supplied with method calls
– no data need be kept between method calls
container can:– choose any available instance to execu
te method – create and remove instances as neede
d for current load implementation notes:
– implement javax.ejb.SessionBean interface
– has a single ejbCreate() method with no parameters
– mark as STATELESS in deployment descriptor
does not exist
ready
newInstance()setSessionContext(sc)ejbCreate()
ejbRemove()
<method>(...)
Enterprise Java Bean ImplementationSimple stateful session bean
Considerations: used for task oriented objects where:
– state needs to be kept between invocations
container responsibilities:– route a method invocation to the appro
priate instance– serialize non transient state variables w
hen passivating– restore non transient state when activat
ing implementation notes
– implement javax.ejb.SessionBean interface
activate and passivate are only needed if you cache computed values
– mark as STATEFUL in deployment descriptor
does not exist
ready
passive
newInstance()setSessionContext(sc)ejbCreate(...)
ejbPassivate()ejbActivate()
<method>(...)
ejbRemove()
Enterprise Java Bean implementationTransactionally aware session
Considerations: used to wrapper (a few) resource oriented o
bjects: – can participate in two phase commit proces
s container responsibilities
– disallow methods not in proper context during a transaction
implementation notes– can mark methods as transactional in DD– also implement javax.ejb.SessionSynchroni
zation interface: afterBegin() - prepare for transaction sta
rt beforeCompletion() - prepare for a comm
it if possible and vote commit or rollback
afterCompletion(true) - finally commit state (all resources voted to commit)
afterCompletion(false) - code to reset to pre-transaction state (rollback occurred)
does not exist
readypassive
newInstance()setSessionContext(sc)ejbCreate(...)
ejbPassivate()
ejbActivate()
non transactional<Method>(...)
ejbRemove()
in trans
afterBegin()
transactional<Method>(...)
afterCompletion( false)
beforeCompletion()afterCompletion(true)
Enterprise Java Bean implementationSelf managed entity bean
Considerations: used for identifiable objects that:
– map to back end data sources not supported by a EJS container implementation
– currently, DB2 UDB only container simply executes the appropri
ate methods implementation notes
– implement javax.ejb.EntityBean interface
create handles check to see if key already exists
post create has active identity activate and passivate are only ne
eded if you cache computed values
– mark BEAN_MANAGED in deployment descriptor
does not exist
pooled
ready
newInstance()setEntityContext(ec)
unsetEntityContext()finalize()
ejbFind<Method>(...)
ejbCreate(...)ejbPostCreate(...)
ejbPassivate()ejbActivate()
ejbRemove()
ejbLoad()
ejbStore()
<Method>(...)
Enterprise Java Bean implementationContainer managed entity bean
Considerations: used for identifiable objects that:
– have no specific requirements for back end resources
container must– manage both the state and the ident
ity of the entity implementation notes
– implement javax.ejb.EntityBean interface
– mark CONTAINER_MANAGED in deployment descriptor
– most methods are generated by container tools
– may implement load, store, activate and passivate for computed values
– IBM implementation of find methods is automatic given a <Bean>FinderHelper
does not exist
pooled
ready
newInstance()setEntityContext(ec) unsetEntityContext()
finalize()
ejbFind<Method>(...)
ejbCreate(...)ejbPostCreate(...)
ejbPassivate()ejbActivate()
ejbRemove()
ejbLoad()
ejbStore()
<Method>(...)
Enterprise Java Beans:Development process (manual)
Define client side components Remote and Home interfaces Key class if necessary (complex keys only)
Provide server side components choose implementation type and code appropriate methods if using IBM Container Managed persistence, define FinderHelper class define DeploymentDescriptor properties in config file
Package one or more beans together compile the java classes and interfaces generate the deployment descriptor.ser files
– java -nojit com.transarc.jmon.util.MakeDescriptors -file <BEAN>.DD create a manifest.stub to describe EJBs to be included create a Java archive file (JAR):
– jar cfvm <IBMWAS>/deployableEJBs/<Bean>.jar manifest.stub *.class *.ser Deploy the bean(s) into one or more container(s)
create the deployed EJB JAR file:– java com.ibm.ivj.ejb.tools.deployment.EJBDeploy <Bean>.jar <IBMWAS>/temp <IBMWAS>/
deployedEJBs/<Bean>.jar add the jar to the desired container properties
– in <IBMWEBAS>/properties/ejs.properties)
Enterprise Java Beans:Development (using admin tools)
Define client side components and implement EJB as before Generate deployment descriptor using JET tool
make sure swingall.jar is in <IBMWAS>/samples/ejs change to <IBMWAS>/samples/ejs execute jet.bat
Deploy the bean(s) using the admin GUI URL is http://<yourserver>:9527 use EJB tabs to deploy new jars don't forget to restart EJS to get access to new EJBs
Some best practices to consider:Programming model perspective
JNDI get initial context in init method do not use to bind non CORBA objects
JDBC consider using Container managed entities instead (for DB2) use connection pooling techniques where possible
JTS consider wrapping unit of work in stateless session bean instead
Enterprise Java Bean clients hold references in session state if possible be aware of remote exceptions
Enterprise Java Bean implementations wrapper task oriented code (new or existing) with sessions wrapper existing (non DB2) data with self managed entities wrapper resource managers with transactionally aware session beans treat stateful session beans like HttpSessions (can go away at any time) use large granularity methods where possible to decrease network traffic:
– return JavaBeans with lots of properties, instead of one at a time– use session beans to make calls to multiple EJB (session or entity)
Some best practices to consider:Development role perspective revisited
Role
Concern
ProgrammingSkills Required
Components Produced
Page Producer
Page Layout and Content
(View)
Application Assembler
Application Flow (Cont
roller)
Bean Builder
Business Logic (Model)
Web Master
Operational Environment (Application)
Java Server Pages, HTML, MIME types
HTTP Servlets, JavaBeans Java Bean
s, EJBs
Configuration Data, Site Usage Statistics
Little or None
Pure Java Non
e
Java + others
Tools WYSIWYG Editors
Java IDE
Admin + EJB deployment
Specialized Wizards
Components Used
JavaBeans, EJBs
Java Beans, EJBs, + others
AllJavaBeans
"Let the right expert do the work."
Some best practices to consider:A top down design perspective
Analyze the object interactions of transitions from task analysis indicate all instances of end user
s, sessions and entities show assumptions ({}) and state
changes ([]) show both request and reply data
where applicable
Bank Customer ATM Account Account
Transfer(1, 2, 100.00)
{lookup acct 1 and 2}
[ id = 1, amount = 5678.22 ]
[ id = 2, amount = 20.23 ]
{create an ATM}
[ amount = 5578.22 ]
[ amount = 120.23 ]
debit(100.00)
credit(100.00)
Key:
User
Session
Entity
request(parms)
reply data
Map to architecture components: map objects with user clients to EJBs data flowing on request and reply define
method signatures– boundaries define method logic
minimize physical boundary crossings (rearchitect if necessary!)
– use session objects where needed to avoid multiple functional calls
– pass JavaBeans where needed to avoid multiple "CRUD" type calls
HTTP Servlets as Controllers exploit benefits of Java Servlets over CGI
JSPs as Views separation of controller and view
Java Beans as a Local Model formalize contract between client and server may directly access back end and eliminate the need for a controller
Self Managed Entity or Stateless Session EJBs as Distributed Models separation of controller and model
Container Managed Entity or Stateful Session EJBs separate persistence from business logic in model
Repeat 3 & 4 as technology changes may skip Self Managed Entities when/if container and server APIs are stand
ardized– build your own persistent container one-time instead– would need to standardize how emitter tools are used
WebSphere Advanced scenarios:Evolution in the context of EJBs
WebSphere Advanced scenarios:An architectural perspective
Client-Server (2 tier) "thick" client programs with direct access to back end resources Java Applications, Java Applets, Java Beans, and connectors/object services
Model-View-Controller (3 tier) supports "thin" browser only clients handle presentation to user "middle tier" application server controls the application flow HTTP Servlets, JSPs, Java Beans and connectors/object services
Distributed Object (n-tier) supports middle tier as a client to back end resources wrappered as EJBs "n" tier because EJBs are implemented using object services/EJBs too HTTP Servlets, JSPs, Object Services, Enterprise Java Beans (EJBs)
Java standards introductions (cause or effect?)
JNDI, JDBC, JTS
Java Server Pages
JavaApplets
Java BeansEJB EJP
HTTP Servlets
Client-Server (2-tier)
Model-View-Controller (3-tier)
Distributed Objects (n-tier)
AdvancedStandard IBM WebSphere support in: Future
IBM WebSphere Advanced Edition:Summary of features
Standalone Java Application
HTTPServlet
JavaServerPage
JavaBean
Client (Java Virtual Machine)Application Compon
ents
JavaApplet
EJBKey
JNDIContext
JTSUser Transaction
EJB Client APIs
EJBHome
EJBRemote Interface
JAVA
JAVA
JAVA
JAVA
JAVA
JAVA
CORBA Object
EJB Client Impls
EJBRemote
Stub
JNDIContext
Stub
JAV
A
EJB HomeStub
CORBA Naming Skel-Impl
Location Service Daemon
Persistent Name Service
IIOP
IIOP
IIOP
IIOP
EJBHome
Skel-Impl
EJBRemote Skeleton
EJBImpl
Container Impl
Enterprise Java Server
Servers
EJBHome Helper
JNDI Context
JNDI Context Stub
JAV
A
JAVA
JAVA
JAVA
IIOP
JDBC
IIOP
DB2 Universal Data Base
IIOP
MQ Series
CICS
...
Back-end
ApplicationAssembler
Bean Builder Deployment tools PlatformComponent provider key:
All of Websphere Standard Set of standards based object services (JNDI, JTS, JDBC) Enterprise Java Server (single process, simple administration and deployment tools)
Everything you need to build n-tier distributed object based applications
top related