J2EE Programming Model Best Practices - IBM · J2EE Best Practices Browser control flow mechanisms...
Transcript of J2EE Programming Model Best Practices - IBM · J2EE Best Practices Browser control flow mechanisms...
IBM WebSphere Application Server
J2EE Programming J2EE Programming Model Best PracticesModel Best Practices
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesRequirements Matrix
There are four elements of the system requirements:business process and application flowdynamic and static aspects of each
Models Dynamic Static
Business Process (contract) Units of work Persistent data
Application Flow (user role) User initiated events Visible data
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesWhat our business does
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line
item (product, quantity)
cancel()
Customer PackerMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
assign()
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesWhat our business does (cont.)Order Entry static object model
show business objects, associated properties and relationshipsunits of work from dynamic model should be in terms of these
0..nLine Item
quantity
Order
+orderIDstatus
Product
+skudescription
Customer
+customerID
0..n customer+product 0..1
openOrder
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesAn example application flow dynamic model
Customer's application flow dynamic modelhigh level requirements captured in a STD of a customertransitions may trigger events on the underlying BPM
OrderDetails
ConfirmSubmit
submitcancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0][quantity < 0]
ok{submit order}
We will examine best practices in terms of the application flow for the customer of an "on line mall"...
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesAn example application flow static modelCustomer application flow static model
one "entry point" object per stateattributes and relationships show dynamic content
Order Details
customerIDorderIDstatus
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Order Status
customerID
Customer Home
Product
productIDdescription
Product Catalog
products items orders
0..nAction Result
message
Confirm Action
orderIDaction
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesWeb enabled distributed object based
Can be considered as a "thin" n-tier architecture …
IIOP ???Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity)
cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
advantage 1: client need not install anything because
browsers are everywhere
advantage 2: business logic does not execute
on web server farm, eliminating need for enterprise access
advantage 3: can share and load balance both
application flow and business logic
HTTPWeb
Application Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
disadvantage: long end-to-end
pathlength
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesProgramming model overviewAfter determining the basic architecture, the next step is to understand the programming model and design issues for each tier:
–components that you develop hosted on that tier–mechanisms used to flow control between components–sources used to flow data between components
Component Control Flow Data Source
Browser HTML, XML, Framesets HTTP requests, JavaScript
URL Query String, POST Data, Cookies
Application Server Servlets, Java Server Pages, Java Beans
sendRedirect(), forward(), include()
Request, Session, Servlet Context
Distributed Object Server
Session EJB, Entity EJB, Java Beans RMI/IIOP JNDI, JDBC, others
Enterprise Server BMP Entity EJB, SessionSynch EJB
beforeXXX(), afterXXX(), ejbXXX() JNDI, JDBC, others
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesBrowser hosted componentsFirst, we will look at various approaches that make use of browser hosted components, like HTML, XML, Framesets and Applets
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
HTTP
Component Control Flow Data Source
Browser HTML, XML, Framesets HTTP requests, JavaScript
URL Query String, POST Data, Cookies
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesComposing pages in our exampleHow would you use framesets or composed pages to map multiple related states into a single page?
ok{submit order}
OrderDetails
ConfirmSubmit
submitcancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Navigation area
Result area
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesUsing custom composed pages
Action Result
Customer Home Order
Statusopen(order)
Product Catalog
add to order
{add item(product, quantity)}
[qty = 0]
OrderDetails
submitcancel
edit line item
{modify item(product, quantity)}
[qty < 0]ConfirmCancel
ok{cancel order}
{create order} Confirm
Openok
ConfirmSubmit
ok{submit order}
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesBrowser control flow mechanismsNext, we will look at when to apply various browser managed control flow mechanisms like HTTP requests, JavaScript and Java applet UI events
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
HTTP
Component Control Flow Data Source
Browser HTML, XML, Framesets HTTP requests, JavaScript
URL Query String, POST Data, Cookies
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesBrowser controlled data sourcesFinally, we will look at when to apply various browser controlled data sources like URL query strings, POST data and Cookies
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
HTTP
Component Control Flow Data Source
Browser HTML, XML, Framesets HTTP requests, JavaScript
URL Query String, POST Data, Cookies
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesWeb page design summaryRule of thumb: separate concerns and minimize the number and size of trips to the server without duplicating logic on the client
Component Best useHTML specify both format and data for a given stateXML/XSL encapsulate state data independently of formatFrame/Windows consolidate multiple states related to same task
Control Flow Best useHTTP GET read only transitions (flow into a state)HTTP POST update transitions (flow out of a state with side effects)JavaScript confirmations, syntactic validations, menus and listsData Source Best UseURL query string keys and other query data to next statePOST data unlimited amounts of form data for updatesCookies data used across the session or multiple sessions
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication server hosted componentsFirst, we need a brief overview of the types of components that can be hosted on a web application server, like Servlets, Java Server Pages, and Java Beans...
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
HTTP
Component Control Flow Data Source
Application Server Servlets, Java Server Pages, Java Beans
forward(), include(), sendRedirect()
Request, Session, Servlet Context
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication architecture mappingNow that we understand the basic component types, the next step is to choose an application architecture that maps physical tiers:
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity)
cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOPWeb
Application Server
HTTP
into logical components that execute in the application server tier:
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
JAVAJAVA
Controller
Entry Fulfillment
Completed
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
IIOPHTTP0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
ModelView
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication architecture mapping (cont.)Model components encapsulate:
–units of work for the business process–logic to access any distributed object servers or back ends
View components encapsulate:
–visible data for the application flow–logic to render the data into the client browser language
Controller components encapsulate:
–user initiated event handlers for the application flow–logic to gather data from model components based on the request–logic to drive the appropriate view components based on the result
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication server control & data flow (cont.)What are the control and data flow mechanisms we have seen so far? between what components?
Source Target Control Flow Data Source
Browser Web server HTTP GET, HTTP POST
URL query string, POST data, Cookies
Web application server Servlet or JSP service(), doGet(), doPost()
HttpServletRequest,HttpServletResponse
Servlet or JSP Access bean Java method call Data structure Java Bean
We will look at the following control flow mechanisms and associated data sources:
Source Target Control Flow Data Source
Servlet orJSP Servlet or JSP forward(), include(), sendRedirect()
Request, Session, Servlet Context
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication server supported data sourcesFinally, we will look at other sources that can be used to pass data from one component to another, such as session state and servlet context
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
HTTP
Component Control Flow Data Source
Application Server Servlets, Java Server Pages, Java Beans
forward(), include(), sendRedirect()
Request, Session, Servlet Context
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesApplication server data source issuesThere are some important issues to consider:
–what are the data sources and when do they best apply?–where should you cache data to minimize back end accesses?
We will discuss each issue separately
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesHttpSessionConsider caching the data structure Java Bean for a state in HttpSession to eliminate extraneous back end accesses
Web Application
Server
ClientWeb
Browser
Order Details Servlet
{repeat}
HTTP GETOrderDetailsServlet?... doGet(req, res)
req.getSession(false).getValue("OrderDetails")
null{getOrderDetails()}
req.getSession(true).putValue("OrderDetails", OrderDetailsBean)
[session = <"OrderDetails", OrderDetailsBean>]
OrderDetailsBeanreq.getSession(false).getValue("OrderDetails")
doGet(req, res)HTTP GET ...{...}
{OrderDetailsJSP}"HTML for Order Details"
{OrderDetailsJSP}"HTML for Order Details"
advantage 2: session shared across
contexts
advantage 1: handles timeout
problem: cache consistency!
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesHttpServlet design approaches
Think about what would happen if we only created a single HttpServlet to control the entire application...
problem 1: only one programmer could work at a
time
problem 2: the code would be rather
complex to handle all the states and
transitions
problem 3: can't use servlet level security, monitoring...
better approach: one servlet per state with dynamic transitions
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}{cancel order}
{modify item(product, quantity)}
add to order{add item
(product, quantity)}
Confirm Open
(order)
okOrderDetails
OrderStatus
Product Catalog
advantage: only one object to code and administer
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesThe "page composition" problemThink about how you would deal with the situation where framesets or named windows cannot be used on the client
adding an item to the order redisplays
catalog page
Customer Home
Product Catalog
Action Result
Customer Home
Order Status
Action Result
Customer Home
Order Details
Action Result
selecting or adding an order displays details
modifying an item, or submit/cancel redisplays order
want to reuse code to render
"substates" of a given page
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesHttpServlet inheritanceUse inheritance and factor common behaviors into an extensible HttpServlet class hierarchy
{check authorization: if not, forward to Login JSP}
Web Application
Server
Product Catalog Servlet
ClientWeb
Browser
OnlineBuying Servlet
HTTP GET ProductCatalogServlet?start=101 doGet(req, res)
"HTML for Product Catalog starting at
item 101"
include( "ProductCatalog",req, res)
doGetOnlineBuying(req, res)
{append directory of user's preferred language to name
and forward}
{catch errors: if any, forward to Error JSP;
otherwise compose page}
advantage 2: subclass methods focus on
gathering data, handling updates
advantage 1: naming convention makes it easy
to extend hierarchy
advantage 3: inherited
convenience methods make developing & maintaining even easier
advantage 4: can declare final & abstract
for enforcement
advantage 5: can develop look and feel separately
could modify include to
generate XML instead
problem: minimizing back
end accesses
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesSummary for HttpServlet design
HTTPServlets control states and associated transitionsJSPs generate the HTML view associated with stateData beans encapsulate data model needed by JSPdoGet() gathers data to display doPost() handles updates and flows to next stateUse sendRedirect after update actions to avoid reload problemDesign JSPs so that they can be composedCapture common look-and-feel in inherited HttpServlets rather than "gateway" servletsLet superclass servlet decide whether to call JSP or generate XML for return to XSLT enabled browsers
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesSummary for servlet design (cont.)
HttpSession should only maintain easily recomputable values to avoid timeout problemCheck keys & remove session to avoid cache consistency problemsUse client-server affinity or persistent sessions to avoid cluster consistency problemServletContext should only cache stable readonly datainit method on HttpServlet can be used to load cache
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesHttpServlet design approaches
Think about what happens when business logic is coded in the HttpServlet...
problem 1: increases code complexity
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}{cancel order}
{modify item(product, quantity)}
add to order{add item
(product, quantity)}
Confirm Open
(order)
ok
problem 4: reduces opportunities for parallel
development by different roles
advantage: code probably achieves the best response time
problem 5: reduces
opportunities for reuse
problem 3: makes maintenance more difficultproblem 2: makes testing
and debugging harder
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesEnterprise Java Bean design points
In this section we will discuss techniques for designing Enterprise Java Beans that provide the benefits of distributed objects to any client application type
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Distributed Object Server
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line item
(product, quantity) cancel()
Customer ShippingMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Business process dynamic model
Browser
0..n 0..n
Line Item
productIDdescriptionquantity
Order
orderIDstatus
Product
productIDdescription
Order Details
customerIDorderIDstatus
Order Status
customerID
Product Catalog
0..n
Product Catalog
Action Result
message
Confirm Action
orderIDaction
Customer Home
products items orders
Application flow static model
HTTP IIOP ???Enterprise Logic/Data
Server
0..nLine Item
quantity
Order
orderIDstatus
Product
skudescription
Customer
customerID
0..n customer
openOrder
product 0..1
Business process static model
Web Application
Server
Application flow dynamic model
OrderDetails
ConfirmSubmit
submit
ok
cancel
OrderStatus
ConfirmCancel
open
Customer Home
Product Catalog
Action Result
{create order}
edit line item
ok
{submit order}
{cancel order}
{modify item(product, quantity)}
add to order
Confirm Open
(order)
ok
{add item(product, quantity)}
[qty = 0]
[qty < 0]
Component Control Flow Data Source
Distributed Object Server
Session EJB, Entity EJB, Java Beans Java, RMI/IIOP JNDI, JDBC, JMS
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesLikely evolution of stateful session EJBsInitially used to cache commonly used session data
–minimizes calls to the back end–serves as a shared cache (affinity is managed by container)
Timeout and failover become issues –update methods write non transient data to backing store–custom creates use a parameter to load data from store–some go as far as to use session synchronization (discussed later)–in either case, cache and cluster consistency become issues
Tends to defeat the purpose of a stateful session EJB as a simple shared cache
–starts sounding a lot like an entity EJB with bean managed persistence (discussed later)
–would be better of with an entity EJB with container managed persistence (also discussed later)
As you might guess, this is a "worst practice" or "anti-pattern"
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesReal Best PracticesInitially used to cache commonly used session data
–minimizes calls to the back end–serves as a shared cache (affinity is managed by container)–servlet clients need HTTPSession to keep handle–mark all but "key data" as transient to optimize passivation
Timeout and failover become issues –update methods write transient data to backing store–custom creates use "key data" to load transient data from store–some go as far as to use session synchronization (discussed later)–"key data" is still lost on node failure
Tends to defeat the purpose of a stateful session EJB as a simple shared cache
–starts sounding a lot like an entity EJB with bean managed persistence (discussed later)
–would be better of with an entity EJB with container managed persistence (also discussed later)
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesSession Enterprise Java beans
Consider a session Enterprise Java bean patterned after each business logic access bean to implement logicWhat are the classes and methods?
Entry FulfillmentCompleted
submit()ship (shipper)
create()
[all items shipped]
purgemodify line
item (product, quantity)
cancel()
Customer PackerMarketing
add line item (product, quantity)
[not all items shipped]pack line item
(product, quantity)
Entry submit()
create()
modify line item
(product, quantity)
cancel()
add line item (product, quantity)
Fulfillment
ship (shipper)
pack line item (product, quantity)
Completed purge
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesSession Enterprise Java Beans
OrderEntry
Access
OrderDetails Servlet
JNDIInitial
Context
OrderEntry
(Session)
OrderEntry Home
home.create()OrderEntry
getOpenOrder(1111){get open order for customer 1111}
OrderDetailsDataremove()
OrderDetailsData
getOpenOrder(1111)
OrderEntryAccess[static instance = OrderEntryAccess]
singleton()
lookup("OrderEntry").narrow()OrderEntryHome
[home = OrderEntryHome]
new()[static instance=null]
issue: business object access beans must deal with
persistence and transactions
advantage 1: no business logic in web application
server
advantage 2: can use caching to minimize
home lookups
tradeoff: remote method call overhead
Use a session EJB in a business logic access bean when required for scalability or isolation
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesEntity Enterprise Java Beans
Consider an entity EJB patterned after each business object access bean to implement peristence layer
0..nLine Item
quantity
Order
+orderIDstatus
Product
+skudescription
Customer
+customerID
0..n customer
openOrder
+product 0..1
Line Item Order
Product Customer
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesEntity Enterprise Java Beans
Order Access
OrderEntry
(Session)
JNDIInitial
ContextOrder
(Entity)Order Home
singleton()
home.findByPrimaryKey(1000){find Order Entity EJB and load CMP fields}
Order
getPi()vi
{set vi into OrderDetailsData}
OrderDetailsData
new().lookup("OrderHome").narrow()OrderHome
[home = OrderHome]new()
{new OrderDetailsData}
{repeat}
getOrderDetails(1000)OrderAccess
advantage: persistence logic provided by EJB container
tradeoff: remotable method call overhead (usually co-deployed)
problem: multiple remotable gets and sets
Use entity EJBs in business object access beans to handle persistence and transaction logic transparently
© Copyright 2001 IBM Corporation. All rights reserved.
Best Practices for WAS V5.0Local (versus remote) interfaces
Local InterfacesTraditional Remote (RMI)
Interface extends EJBObject
Interface extends EJBLocalObject
Home extends EJBHome Home extends EJBLocalHome
Remote method calls More efficient local calls
Location Independent Client and EJB need to reside in the same JVM
Parms passed by value Parms passed by reference
Remote exceptions thrown on methods Regular Java Exceptions
Use narrow() to cast Use regular Java class cast
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesDependent value classes
public abstract CustomerBean implements EntityBean {
...// container-managed persistent fields
...public abstract AddressData getShippingAddress();public abstract void setShippingAddress(AddressData data);public abstract AddressData getBillingAddress();public abstract void setBillingAddress(AddressData data);
// method worth promoting to interfacepublic CustomerData getData() {
CustomerData data = new CustomerData();... data.shippingAddress = getShippingAddress(); data.billingAddress = getBillingAddress(); ...return data;
}}
no need to flatten fields from dependent value classes in CMP fieldsbest not to promote get/set fields, though even less crucial if local
<cmp-version>2.x</cmp-version><abstract-schema-name>
CustomerBean</abstract-schema-name><cmp-field id="CMPAttribute_1">
<field-name>id</field-name></cmp-field><cmp-field id="CMPAttribute_2">
<field-name>name</field-name></cmp-field><cmp-field id="CMPAttribute_3">
<field-name>shippingAddress
</field-name></cmp-field><cmp-field id="CMPAttribute_4">
<field-name>billingAddress
</field-name></cmp-field>
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesEJB Query language (EJBQL)Design issue:
how do you implement custom finders?single and multiple cardinalitywith and without CMRindependent of relational persistence mechanism
0..nLine Item
quantity
Order
@idstatus
Product
@skudescription
Customer
@idname
0..n customer
openOrder
@product 0..1
Address
line1, line2,city, statezip, country
shipping
billing
Shipper
@idcompany
shipper
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesEJB Query language (EJBQL)After:
custom finders specified in the deployment descriptorindependent of persistence mechanism (theoretically)can follow relationships, avoiding complex joins in finders
<entity id="ContainerManagedEntity_3"><ejb-name>Order</ejb-name> ...<query><query-method><method-name>findOrdersInState</method..<method-intf>LocalHome</method-intf><method-params><method-param>String</method-param>
</method-params></query-method><ejb-ql>SELECT object(o) from Order o
WHERE o.status=?1</ejb-ql>
</query></entity>
Deployment descriptor fragment:public interface OrderHomeextends EJBLocalHome {
public Order create(OrderData data
) throws CreateException;
public Order findByPrimaryKey(OrderKey key
) throws FinderException;
public Collection findOrdersInState(String status
) throws FinderException;}
Local Home definition:
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesMessage Driven Beans (MDB)Design issue:
how do you enable asynchronous processing? loose coupling, but with reliable delivery and 2PCusually associated with major transitions in the business process
Entry FulfillmentCompleted
submit()ship (shipper)
[all items shipped]
purgemodify line
item (product, quantity)
cancel()
Customer ShippingMarketing
add line item (product, quantity)
[no items]
pack line item (product, quantity)
[items to ship]
assign()create()
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesMessage Driven Beans (MDB)develop/generate a message driven bean (MDB) for major transitionsget container managed messaging (CMM) qualities of serviceclients send messages through JMS to trigger MDB
Typical Message Driven Bean class:public class OrderSubmitMsgHandler implements MessageDrivenBean {private transient MessageDrivenContext context = null;public void ejbCreate() {}public void ejbRemove() {}public void setMessageDrivenContext(MessageDrivenContext mdc) { context = mdc; }
// Message acknowledge and database update participatepublic void onMessage(Message inMessage) {
OrderSubmitMsg msg = (OrderSubmitMsg) inMessage;try {
// The access bean passes thru to the session EJB to handle unit of workOrderFulfillmentAccess.singleton().submit(msg.order);
} catch(OrderHasNoItemsException e) {
// The access bean passes thru to the session EJB which sends another messageOrderFulfillmentAccess.singleton().alert(e);
}}
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesMessage Driven Beans (MDB)may want to use local interface to session as "alternate" access path
however, co-deployment and no local calls perform nearly as well
SessionClient
Access
J2EE Client App
SessionRemoteInterface
JavaSession
BeanImpl
SessionLocal
Interface
EntityClient
Access Java
EntityLocal
Interface Java
EntityBeanImpl
Java
Session Alternate Access
Java
MessageDriven Bean
JavaWeb
Services Servlet
Java
IIOP
JMSWeb
Services Client
Asynch Services
ClientHTTP
Java Java
1.
2.
12.
3. 4. 5.
6.7.8.9.10.11.
14.13.
15.
16. 23.
24.
25.26.
27.28.
39. 40.
17.31. 18.
19.20.
21.22.
29.
30.
32.
33.34.
35.36.
37.
38.
© Copyright 2001 IBM Corporation. All rights reserved.
J2EE Best PracticesSummary for EJB design
Consider session EJBs in business logic access bean to get benefits of distributionUse stateless session EJB s wherever possible to maximize scalability characteristics of applicationOnly use stateful session EJBs when timeout and failover of cache are not issues, otherwise choose entity EJBsConsider entity EJBs in business object access beans to separate business logic from persistence logicUse custom creates, finds, gets, sets and updates in entities tominimize number of remotable callsTreat all entity EJBs as CMPs when programming for functional requirements