1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach Yourself J2EE in 21 Days phần 8 pot

113 312 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Teach Yourself J2EE in 21 Days Phần 8 Pot
Trường học University of Technology
Chuyên ngành Computer Science
Thể loại Bài viết
Năm xuất bản 2002
Thành phố New York
Định dạng
Số trang 113
Dung lượng 828,08 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

• Discover some of the J2EE patterns that are applied in the case study• Suggest how other J2EE patterns can be used to improve the design of the casestudy Today’s intention is to invest

Trang 1

pre-In line 6, the HTML table borderattribute is enclosed in quotes so that it is valid XML(the same is also true for line 10 and the colspanattribute).

Line 12 uses one rule to match the <location>or <skill>elements Finally, the name ofthe selected node is inserted into the output stream using the name()function in line 13.Figure 17.2 shows the result of applying the table.xslstylesheet from Listing 17.10 tothe jobs.xmlfile

L ISTING 17.11 Continued

F IGURE 17.2

The XML to HTML table transformation.

XSL supports significantly more complex transformation rules than those shown so far.The next section will provide an overview of some of the additional XSL features

Trang 2

Using Stylesheet Elements

XSL defines about twenty elements for transforming XML documents So far, you haveseen the basic <xsl:template>element for defining template rules and the <xsl:apply- templates>and <xsl:value-of>rules for including data in the output document

Many transformations can be defined just using these three elements However, some ofthe more complex requirements need additional support from XSL

Processing Whitespace and Text

By default, an XSL transformation retains the whitespace in the original document Thismay not be required for the following reasons:

• The whitespace is generally ignored when processing the output

• Users browsing the transformed document may find the whitespace misleading orannoying

• Some output document formats may be whitespace sensitive, so the transformationmust control the way whitespace is written to the output

The <xsl:strip-space>tag can be used to strip leading and trailing whitespace from anelement’s body The tag takes an elementsattribute that defines from which elements tostrip the whitespace Elements are selected using the XPath notation

Listing 17.12 shows the simple.xslstylesheet shown in Listing 17.2 enhanced to stripwhitespace from all elements

L ISTING 17.12 Full Text of simpleStrip.xsl

Applying this stylesheet to the jobs.xmldocument produces the following output:

LondonMust like to talk and smokeCigar makerCriticWashingtonMust

➥be honestTree surgeon

No whitespace has been included but, as you can see, this is not particularly readablebecause the whitespace between the elements has been lost You could selectively stripwhitespace from elements using tags, as shown in the following:

<xsl:strip-space elements=”jobSummary|job”/>

But this will still retain multiple spaces in the non-stripped elements

Trang 3

Inserting whitespace into the output stream is best done using the <xsl:text>element.Any whitespace inside the <xsl:text>element is retained You could rewrite the defaultrule for all elements to include a single blank line before each element, as shown inListing 17.13.

L ISTING 17.13 Full Text of simpleSpace.xsl

Critic Washington Must be honest Tree surgeonWhitespace is automatically stripped from the stylesheet, which is why the indented

<xsl:apply-templates/>tag does not insert any whitespace before the output text.The <xsl:text>tag is also used to insert text containing XML special characters (such

as <and &) into the output stream These characters are defined in the stylesheet usingtheir character reference form (such as &lt;) and are output in the same format

Wrapping the symbols inside an <xsl:text>element with the escapingattribute set to yeswill output any special symbols as simple Unicode charac-ters The <xsl:text>element is most often used when the output document is not anXML document, or the output is not well formed XML

Trang 4

The following example shows one way of inserting a piece of JavaScript into your Webpage (using comments, as described in the “Adding Comments” section later in thischapter, is a better approach):

Caution

Trang 5

The following example shows a better solution to inserting JavaScript in an HTML page:

<description>Must like to talk and smoke</description>

<! skills list for winston >

Trang 6

<xsl:template match=”job”>

<job customer=”<xsl:value-of select=’./customer’/>”

To get around the XML restriction of not allowing elements to be defined inside

attribut-es, XSLT stylesheets let you insert the value of elements inside attributes by enclosingthe XPath name in braces, as shown in the following:

<xsl:apply-templates select=”./*[name()!=’customer’ and name()!=’reference’]”/>

If you want to convert the new style jobelement (with attributes) back to the one withnested elements, you use the following rule:

Creating and Copying Elements

In the previous section, you learned how to convert one XML document to another by verting nested elements into tags But what do you do if you want to convert an attributeinto an element where the attribute value is the name of the element, or vice versa?

con-As a simple example, consider a Deployment Descriptor (DD) for two Session beans, asshown in Listing 17.14

Trang 7

L ISTING 17.14 Full Text of dd.xml

1: <?xml version=”1.0” encoding=”UTF-8”?>

2: <! DOCTYPE ejb-jar PUBLIC

➥’-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN’

Trang 8

The second rule in the previous example (<xsl:element name=”{./session-type}”>)ensures that the session-typechild element is not included in the output document.

Sadly, there is one major problem with the previous example All other elements are put using their text values, the element start and end tags and attributes have been lostfrom the document The problem can be overcome using the <xsl:copy>element

out-The <xsl:copy>element is used to copy elements from the XML source to the outputdocument The following rule is an identity transformation rule (the document is copiedwithout any changes):

of the matched XML node; otherwise, no output will occur

The full stylesheet for transforming the old style DD into the new style is shown inListing 17.15 The output from applying this stylesheet is shown in Listing 17.16

L ISTING 17.15 Full Text of session.xsl

Trang 9

L ISTING 17.16 Applying session.xsl to dd.xml

1: >java org.apache.xalan.xslt.Process -in XML/dd.xml -xsl XSL/session.xsl 2: <?xml version=”1.0” encoding=”UTF-8”?>

3: <! DOCTYPE ejb-jar PUBLIC

➥’-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN’

Attributes and Attribute Sets

In the example jobSummarydocument in Listing 17.3 and the stylesheet table.xslinListing 17.10, you might like to be able to use a hyperlink to link the customer name to aURL of the form

Trang 10

Sometimes, the same attributes must be defined for many different tags This is a mon requirement when applying styles to HTML tables Consider making every cell inthe table contain text with a blue sans-serif font You could define the style separately forevery cell in the table, but this is hard to maintain should the style requirements change.

com-Alternatively, you could use Cascading Style Sheets (CSS), but the most popularbrowsers do not support CSS in a consistent manner An XSL solution is to use anattribute set

The <xsl:attribute-set>element defines the attributes you can apply to multiple ments An <xsl:attribute-set>defining a blue sans-serif font is as follows:

<TD><FONT face=”Arial,sans-serif” color=”blue”>location</FONT></TD>

<TD><FONT face=”Arial,sans-serif” color=”blue”>London</FONT></TD>

</TR>

Trang 11

<TD><FONT face=”Arial,sans-serif” color=”blue”>skill</FONT></TD>

<TD><FONT face=”Arial,sans-serif” color=”blue”>Cigar maker</FONT></TD>

</TR>

<TR>

<TD><FONT face=”Arial,sans-serif” color=”blue”>skill</FONT></TD>

<TD><FONT face=”Arial,sans-serif” color=”blue”>Critic</FONT></TD>

Trang 12

Additional XSL Elements

XSL supports a number of elements that can provide program language like capabilitieswithin a stylesheet Using these elements requires a good knowledge of the XPath nota-tion Because you have only seen some of the XPath notation, you will only look verybriefly at the elements that support programming capabilities

Numbering Elements

A common requirement for many transformations is to insert numeric data into the put document, often to produce numbered lists

out-The <xsl:number>element is used to insert numbers into the document By default (that

is, without attributes), this element inserts a count of the position of a context node in alist of elements of the same type

To number the skills defined by a particular job, you could use the following rule:

Attributes can be supplied to the <xsl:number>element to determine what numeric value

is inserted The level=”any”attribute is used to count all occurrences of the same type

of node, regardless of where the node occurs in the document tree structure The ing example adds numbers to job definitions:

L ISTING 17.18 Full Text of tableCount.xsl

Trang 13

The <xsl:number>tag can also be used to

• Insert numeric data obtained from an element or attribute in the XML source ment

docu-• Count occurrences of a node

• Count nodes from a given start point

• Use letters or roman numerals instead of decimal integers or insert leading zeroes

to make fixed-width numbers

L ISTING 17.18 Continued

Trang 14

• <xsl:choose> Defines a list of choices, only one of which will be included.

• <xsl:when> Defines a choice for an <xsl:choose>element

• <xsl:otherwise> Defines the default choice for an <xsl:choose>element if no

<xsl:when>element is matched

The <xsl:if>and <xsl:when>elements use a testattribute that evaluates an XPathexpression and includes the element body if the test is true

The following example tests if a Session bean from a DD is a stateless bean:

Trang 15

Other XSL elements include the following:

• <xsl:sort> Used to sort elements by alphabetic or numeric order

• <xsl:include>and <xsl:import> Import rules from other stylesheets

• <xsl:variable> Used to define variables that can be used in other XSL elements

• <xsl:template> Used to define templates that can be inserted in different parts

of the transformed output (parameters can be used to customize each instance of atemplate)

As you can see, XSLT provides a powerful transformation language that really is toolarge and complex to cover in one lesson Today’s work on XSLT has been designed togive you an overview of what XSLT can do For more information on XSLT, refer to the

specifications on the W3C Web site or read the book Sams Teach Yourself XML in 21

Days from Sams Publishing.

XSLT Compilers

One drawback to XLST stylesheets is performance An XLST processor, such asXALAN, must read in the stylesheet and build an internal structure representing the rulesthat must be applied The processor must then read in the XML document and matcheach element to the rules defined in the stylesheet and generate the required output All

of this takes time

One way to improve performance is to preprocess the stylesheet to create a custom gram that will apply the one stylesheet to an XML document in an efficient manner.Such a technology is called an XSLT compiler This is a fast changing area of XSL tech-nology, but the original XSLT compiler, called xsltc, developed by Sun Microsystems isnow developed and maintained by the Apache project

pro-Apache provides the xsltccompiler used to compile an XSL stylesheet into a translet (a

set of Java classes) An associated runtime processor is used to apply the compiledtranslet to an XML document and perform the XML document transformation

Trang 16

Summary

Today you have looked at transforming XML documents into other data formats TheXSLT standard defines an XML stylesheet format that specifies how to transform anXML document into a new format XSLT is commonly used to transform XML data intoHTML for presentation by a Web browser

An XSLT stylesheet defines a set of rules Each rule

• Is matched against elements in an XML source document

• Defines transformations that are applied to the matched element to create the formed data

trans-• Can be applied to a selected element or multiple elements including a completetree hierarchy of elements

• Uses the XPath notation to match XML elements (the same XPath notation is alsoused with XPointers in XML documents)

A new technology designed to address some of the performance problems of XSLTprocessors, such as Apache XALAN, is an XSLT compiler An XSLT compiler has twocomponents:

• A compiler than generates a translet (a set of Java classes) from an XSLTstylesheet

• A runtime processor that applies a translet to an XML document to perform thetransformation

The XSL technology also identifies a portable device independent grammar (XSL-FO)for defining formatting requirements and the document data XSL-FO is not being wide-

ly adopted by the industry at the present time

You have now finished your excursion into XML Tomorrow, you will return to Java gramming and the J2EE platform to study Java and J2EE design patterns

Trang 17

Q What are the two components of XSL?

A XSLT defines a language that is used to write stylesheets that will transform an

XML document into a different format

Formatting objects, or XSL-FO, specifies a device-independent grammar for ing the format of a transformed XML page

defin-Q What are three techniques for applying an XSLT stylesheet for a Web client?

A • Send the XML document and stylesheet to the client for processing

• Convert the XML into an HTML file, store the file on the server, and sendthe file to the client to satisfy future HTTP requests

• Transform the XML data on the server for every HTPP request for the data

Q Which XSL element is used to insert the body of a matched XML tag into the output document expanding any nested elements?

A <xsl:apply-templates/>

Q What do the . , , // , and @nameXPath shortcuts expand to?

A .expands to self::node() expands to parent::node()//expands to descendent-or-self::node()

@nameexpands to attribute::name

Q What are the XSL elements for inserting a comment, inserting an element, inserting an attribute, and copying elements?

Trang 20

To display this TLD document, you will need to write a stylesheet that defines rules forthe following transformations:

• Put the tag library name in a <H1>element

• Define a <TABLE border=”1”>to contain all the tags

• Highlight each tag name using a <STRONG>element

• Put each tag in a row in the table and put the name, body content, all the attributesand all the variables each in their own cell

• Put the attribute lists in their own table

• Put the variable lists in their own table

Listing 17.20 shows a suitable HTML page containing one row that meets the previouslylisted requirements

L ISTING 17.20 Transformed HTML Output

Trang 21

F IGURE 17.4

Applying

Trang 22

of those creating the system architecture and their understanding of the ities of the platform on which they are delivering that system.

capabil-The patterns movement within software attempts to capture some of the ence of successful architects and designers so that it can be applied more wide-

experi-ly The exploration of platform-specific patterns can also help designers toapply appropriate patterns in the right place using the right technologies AsJ2EE technology has matured, J2EE-specific patterns have been discovered thatshould make your life as a J2EE designer and developer easier

Today, you will

• Explore how the use of patterns can improve the design of systems

• Examine some of the J2EE-specific patterns currently documented

Trang 23

• Discover some of the J2EE patterns that are applied in the case study

• Suggest how other J2EE patterns can be used to improve the design of the casestudy

Today’s intention is to investigate the role of J2EE-based patterns and see how such terns can be applied in the context of the case study

pat-J2EE Patterns

Being a software designer, developer, or architect is not an easy job To be truly effective,you must combine an understanding of the features required—the so-called problemdomain—with a knowledge of the technologies and products from which the solutionwill be built It is difficult for most practitioners to keep abreast of changing technologies

in parallel with actually delivering applications to aggressive timescales What is needed

is some help to understand the best way to apply technologies and solve common designproblems, rather than having to learn from trial and error Patterns, and specifically in thecontext of this book, J2EE patterns, can help you to do this

What Are Patterns?

To understand the intent of patterns, it is helpful to understand a little bit of their ground

back-The original inspiration of the software patterns movement is the work of the architectChristopher Alexander His considerations of how we design buildings led him to identi-

fy and document common features of successful buildings These common design

fea-tures were christened patterns, and the documentation of a related set of them is termed a

pattern language Alexander’s work can be explored in his writings, such as his book, The Timeless Way of Building.

An architect who designs buildings is constrained only by the qualities of the materialswith which the building can be constructed together with cost constraints and certainphysical laws (such as gravity, for example!) This leads architects to experiment withdifferent forms of building, based on new materials and fashions in design Some ofthese experiments are successful and turn up whole new ways of living and working.Many more experiments create buildings that are uninhabitable and are torn down in arelatively short time Most architects need to build useful buildings that form a pleasantenvironment for those who live and work in them The intention of Alexander’s patterns

is to provide a set of proven building blocks on which such architects can base theirdesigns

Now, consider the preceding paragraph in software terms

Trang 24

An architect who designs software systems is constrained only by the technologies withwhich the system can be constructed together with cost constraints and certain physicallaws (such as available bandwidth!) This leads architects to experiment with differentforms of system, based on new technologies and fashions in design Some of theseexperiments are successful and turn up whole new styles of application Many moreexperiments create applications that are unusable and are discarded in a relatively shorttime Most architects need to build useful applications that create a pleasant experiencefor those who live and work with them The intention of software patterns is to provide aset of proven building blocks on which such architects can base their designs

As you can see from this comparison, the motivations and intentions of architectural andsoftware patterns have much in common

So, what is a pattern? A short definition of a pattern is “A solution to a problem in a text.” Essentially, a pattern is a reusable idea on how to solve a particular problem found

con-in the domacon-in of architecture or design, whether that be physical buildcon-ings or softwaresystems The key aspect of patterns is that they are proven solutions—you discover pat-terns, you don’t invent them!

The concrete form of a pattern is a document describing certain aspects, including thefollowing:

• A statement of the problem that the pattern addresses This can include a list of

conflicting requirements and issues that need to be balanced—known as forces.

• Contexts in which the pattern is known to work

• A description of the solution, possibly including the detailed workings of the tion as it is applied in one context For example, a software pattern may includecode samples

solu-A pattern description may also set out different strategies within the pattern Thesedescribe different approaches to solving the problem, possibly using different technolo-gies or techniques, while still applying the same underlying principle

Although patterns have common central aspects, there is no fixed way of documenting apattern Certain groups of patterns and pattern languages will adopt their own style ofdocumentation that suits their needs The main thing is that it is understandable andaccessible

If you want to investigate the general concept of patterns, the philosophy behind them,and the work of Christopher Alexander, try the following locations:

• “Christopher Alexander: An Introduction for Object-Oriented Designers” hosted athttp://g.oswego.edu/dl/ca/ca/ca.html

Trang 25

• “Some Notes on Christopher Alexander” hosted at http://

www.math.utsa.edu/sphere/salingar/Chris.text.html

Why Use Patterns?

The intent of patterns, then, is to provide a certain level of what might be termed tilled wisdom.” If people are lucky enough to work alongside a skilled architect ordesigner when they are learning their trade, they will gain such “wisdom” by osmosis.Patterns help the propagation of such wisdom so that the written pattern becomes a way

“dis-of gaining some “dis-of the wisdom, even if you do not work alongside such a luminary.The patterns become a toolchest for the designer or architect from which they can select.These tools can help them create an efficient, robust, and flexible solution As such, thedesigner or architect must familiarize themselves with the patterns to the extent that theybecome adept at identifying the type of problem each pattern addresses and the pattern’scontext In doing so, they can ensure that they select the right pattern or combination ofpatterns for the task at hand

It is important to note that patterns are a guideline for a solution—not a solution in and

of themselves Although some design tools now provide templates for the tion of common patterns, you cannot just drag-and-drop patterns into an application toform a solution As a chef will adapt a recipe to suit the ingredients available and thetaste of the guests, so a designer may adjust the implementation of a pattern to suit thespecific context

implementa-Types of Patterns

Patterns occur in all aspects of life, from spiders’ webs to the way a school works Somepatterns are small and specific while others are general and wide-ranging The same istrue of the patterns found in the realm of software The following are some commontypes of patterns:

• Architectural patterns define the overall style of the system and frequently includephysical partitioning and infrastructure considerations as well as the software itself

• Design patterns work at the level of software artefacts, such as classes and nents, and describe ways in which such artefacts can be built and combined tosolve common problems

compo-• Idioms are ways of solving a particular problem in a given environment, such as alanguage or platform Some idioms are the embodiment of a pattern for a particularenvironment For example, the Java mechanisms around the Cloneableinterfaceand the reflection API are idioms that embody more general creational patterns

Trang 26

The concept of patterns applied in the field of software was popularised mainly by the

book Design Patterns—Elements of Reusable Object-Oriented Software written by

Gamma, Helm, Johnson, and Vlissides This is commonly referred to as the ”Gang ofFour” book, or GoF for short As its name suggests, this book contains a set of designpatterns that are independent of platform and language Many software patterns, includ-ing the J2EE patterns examined later, reference GoF patterns to help the reader under-stand aspects of the pattern being described

Because patterns are found at different levels, the design of a system can involve theapplication of patterns inside patterns An architectural pattern may define tiers or ser-vices from which the system is built The contents of these tiers and services may bespecified in terms of groups of components that conform to design patterns These com-ponents, in turn, may be implemented using language- or platform-level idioms

Sets of interlocking patterns have been discovered that form a toolchest for a particularcontext or at a particular level These pattern languages help to promote consistent andcoherent use of patterns One such context is the J2EE platform, and it is a pattern lan-guage for this environment that will be explored today

J2EE Patterns

The term J2EE patterns is used to refer to a set of patterns that have been identified

within J2EE-based solutions These patterns describe how to apply J2EE technologies toaddress common problems found when creating modern, distributed systems As such,they fit the criterion stated earlier that they are “a solution to a problem in a context.” Inthe case of J2EE patterns, that context is the J2EE platform and the typical applicationarchitectures used when building J2EE applications

Some patterns come with the territory in that they are found within the J2EE platformitself However, the term J2EE patterns tends to refer to patterns that can be appliedwhen creating systems on top of the J2EE platform

Some J2EE patterns are simply direct implementations of previously identified patternsusing J2EE technologies An example of this would be the use of publish/subscribe whenapplying JMS Other patterns are specific adaptations of known patterns for J2EE-oriented issues An example of this is the Session Facade pattern, discussed later in thesection on “Session Facades and Entity EJBs,” that encourages correct use of Entity EJBs

Trang 27

Given that all J2EE patterns share a common context (namely, J2EE), they form a patternlanguage within that context Some J2EE patterns are built on concepts from J2EE pat-terns or include them as part of a suggested implementation.

The set of J2EE patterns laid out here (and in other places) does not form a closed set from which J2EE applications can be built An architect or design-

er can apply generic patterns or architectural patterns as they see fit when creating a J2EE-based solution The J2EE-specific patterns simply provide a known set of J2EE-oriented solutions.

There are various places where you can find information on patterns:

• There are now many general patterns books and repositories These include theGoF book, the Pattern-Oriented Software Architecture (POSA) book series, thePattern Languages of Programming (PLoP) book series, and the Hillside onlinepattern resources hosted at http://www.hillside.net/

• J2EE-specific pattern information is available through the Sun Java Center patterns

documented in the Core J2EE Patterns book The Sun J2EE Blueprints patterns are

available at the J2EE Blueprints Web site(http://java.sun.com/blueprints/enterprise/), the proposed J2EE patternsare available at TheServerSide.com (http://www.theserverside.com/pat- terns/, and many patterns with J2EE-related content are available on IBM’sDeveloperWorks Web site at http://www.ibm.com/developerworks/patterns/

• Some products, such as Together/J, Rational Rose, and Aonix Component Factory,provide templates and documentation to help you build systems based on commonpatterns

In all cases, the patterns are embodied in documentation and examples

Applying J2EE-Specific Patterns

Now that you understand the rationale and intent of patterns, how can you apply them toyour J2EE applications? To do this, you must understand the J2EE design context, andyou must also become familiar with the patterns themselves

Trang 28

Applying Patterns in a Context

Most of the patterns defined for the J2EE platform range between the design and tecture levels The most common J2EE architecture is largely assumed—a 3-tier businesssystem—as the context for these patterns You may be able to apply individual patterns indifferent styles of architecture, but as a pattern language, the current J2EE patterns aresquarely targeted at a 3-tier, Web-based business system The 3 tiers are usually classi-fied as the presentation or Web tier, the middle or business tier, and the integration ordata tier

archi-As well as consisting of multiple tiers, the target architecture is roughly based on theModel-View-Controller (MVC) principle MVC is a form of pattern that can be applied

at several levels At the GUI level, it splits the responsibilities for interacting with theuser between a data model, a presentation-oriented view, and a controller to govern theinteraction At the architectural level, this translates into entity EJBs (and various othercomponents) providing a data model, servlets and JSPs providing the view, and SessionEJBs providing the controller or business logic Separating concerns in this way delivers

a lot of flexibility An example of this is that the model and controller (the data and thebusiness logic) can be combined with a variety of views to expose the same functionality

to different clients This is shown in Figure 18.1

F IGURE 18.1

Multiple views for

dif-ferent types of client

within an MVC

archi-tecture.

Integration Client

Browser Client

Mobile Client

XML Web component

HTML Web component

WAP Web component

XML Request XML Response

HTML Request HTML Response

WML Request WML Response

Session and entity EJBs J2EE Server

Given this context, and given that an overall application style is in place, why do youneed more patterns? Well, the purpose of applying patterns within an n-tier application

generally relates to the systemic qualities of the application Systemic qualities,

some-times called non-functional requirements, refer to qualities such as maintainability, sibility, scalability, availability, and so on By applying the patterns outlined today, youshould be able to improve at least one of these systemic qualities in your application, if

Trang 29

exten-not several When the case study is examined later, the impact on systemic qualities ofthe patterns applied is also considered.

If you are designing an application from scratch, it will be second nature to think ofapplying patterns to the design process However, many times you will be working with-

in a pre-defined architecture or with an existing application This does not mean that terns no longer apply It is quite possible to apply patterns to existing applications toimprove them It may be that the original design was not well thought out, or that it usedthe technologies in a nạve way (quite common when technologies are new) A patterncan be retro-fitted to part of the application to improve the systemic qualities of the

pat-application and to generally clean it up This process is called refactoring, and is a key

element in many software processes As part of examining the case study, several tial refactorings will be considered

poten-The last thing that you need before examining the case study is knowledge of the terns themselves

pat-Generic Patterns

Table 18.1 lists some common, generic patterns that are documented in the GoF book

T ABLE 18.1 Common GoF Patterns

Pattern Name Pattern Description

Proxy Provide a surrogate for another object or component to control access to it or

enable access to it Decorator Add a variable level of functionality dynamically with the ability to plug in or

remove components or filters as required (sometimes also known as wrapper or pipes and filters)

Singleton Provide a single instance of a component and a global point of access to it Iterator Provide sequential access to a collection of objects in a way that is independent

of the underlying representation Observer Define a relationship between components so that a change in the state of one

of them causes a notification of this change to be delivered to the others Façade Provide a unified interface for a subsystem, thereby hiding underlying com-

plexity Command Encapsulate a request with its data so that it can be presented and executed as a

whole, without having to specify many different processing methods

Trang 30

J2EE Presentation-Tier Patterns

Table 18.2 lists patterns that have been identified around the presentation (or Web) tier of

an n-tier J2EE application The origin of each pattern is denoted using initials—SJC (SunJava Center), BLU (Sun J2EE Blueprints), TSS (TheServerSide.com)

T ABLE 18.2 Common J2EE Presentation-Tier Patterns

Pattern Name Pattern Description

Front Controller (SJC) A servlet (or JSP) intercepts the request from the user and routes or

“adds value” to the request.

Intercepting Filter (SJC) Provide a Decorator-style (GoF) filter chain as part of a Front

Controller.

View Helper (SJC) Use a JavaBean or custom JSP tag to encapsulate functionality and

separate Java functionality out of a JSP.

Composite View (SJC) Compose a JSP from several different sub-components to provide a

typical, multi-panel Web page view.

Dispatcher View (SJC) A Front Controller (SJC) intercepts and routes (or dispatches) a

request to a JSP (or view) The view or its View Helpers (SJC) retrieve the content and/or data required to populate the view.

Service to Worker (SJC) A Front Controller intercepts and routes (or dispatches) a request to a

JSP (or view) The Front Controller (SJC) (or its helpers) retrieves the content and/or data required and passes this to the view as JavaBeans.

Service Locator (SJC) A client-side shared helper object caches frequently used EJB home

interfaces and dispenses EJB remote references on request.

J2EE Business-Tier Patterns

Table 18.3 lists patterns that have been identified around the business (or middle) tier of

an n-tier J2EE application The origin of each pattern is denoted using initials—SJC (SunJava Center), BLU (Sun J2EE Blueprints), TSS (TheServerSide.com)

T ABLE 18.3 Common J2EE Business-Tier Patterns

Pattern Name Pattern Description

Session Facade (SJC) A Session EJB provides a Facade (GoF) to shield entity EJBs

from direct client access and to obscure the data schema from the client.

Trang 31

Business Delegate (SJC) A client-side object hides EJB-specific (or JMS-specific)

inter-action and exposes local business-oriented methods.

Value Object (SJC) Provide a snapshot of underlying data to be used as a

conve-nient data parcel between client and server to avoid chattiness (excessive network traffic between client and server).

Value Object Builder (SJC) A constructor of Value Objects (SJC) from disparate

server-side data sources It presents one Value Object-based interface for a set of varied business data.

Composite Entity (SJC) Create a coarse-grained business entity from a set of

fine-grained data objects, such as entity EJBs or DAOs.

Value List Handler (SJC) Have a session EJB act as a data cache and provide

single/multiple data element Iterator (GoF) capability Page-by-page Iterator (BLU) A variant of Value List Handler (SJC).

Fast Lane Reader (BLU) Retrieve data for reading directly from the database for

speed, write data back via entity EJBs for transactions and consistency.

J2EE Integration-Tier Patterns

Table 18.4 lists patterns that have been identified around the integration (or data) tier of

an n-tier J2EE application The origin of each pattern is denoted using initials—SJC (SunJava Center), BLU (Sun J2EE Blueprints), TSS (TheServerSide.com)

T ABLE 18.4 Common J2EE Integration-Tier Patterns

Pattern Name Pattern Description

Data Access Object (SJC) Encapsulate data access behind a common interface that can be

implemented in different ways for different data sources.

Typically used for data access in servlets and Session EJBs to encapsulate direct database access.

Service Activator (SJC) Allow an EJB to be called on receipt of an asynchronous

Trang 32

Patterns Within J2EE

As noted previously, certain patterns occur within the J2EE environment itself, includingthe following:

• The Proxy pattern (GoF) is used widely in J2EE Examples include RMI stubs asclient-side proxies and EJB objects as server-side proxies

• An EJB home interface acts as a Singleton (GoF) for the creation of EJB instances

• The servlet filters provided as part of J2EE 1.3 are a form of the Intercepting Filterpattern (SJC)

There are many other patterns that are applied within the Java and J2EE environments

Patterns in Context

You now know some of the common patterns that can be applied in J2EE applications

Using this knowledge, you can analyse the case study followed throughout the book tosee how they can be applied

Analysing the Case Study

Patterns are usually best understood in context It helps to understand the intention of thedesign (and its associated code) and what it is trying to achieve so you can understandwhy a particular pattern helps in that situation By examining the code for the case study,this section intends to

• Identify some of the places where J2EE patterns have been applied in the casestudy

• Examine some of those patterns in detail, including how the pattern looks in code

• Consider what other patterns could have been applied in certain places and thechanges that would be required to use those patterns

• Understand why other J2EE patterns are not relevant to the design of the casestudy

The intention is to look at the central patterns that occur (or could occur) within the casestudy This section will not contain an exhaustive list of all the patterns used

One important objective is to point out at each stage why the patterns are useful Thisprincipally takes the form of indicating which systemic qualities the pattern improves,such as maintainability, extensibility, or scalability, and also any systemic qualities thatmay suffer due to the pattern being applied

Trang 33

When examining any design, it is important to understand the context in which designdecisions were made In this case, it is important to understand that the case study is, inplaces, intentionally simplistic There are two reasons for this:

• The case study is essentially a learning tool Use of production-level code cansometimes obscure (or unnecessarily complicate) the underlying principles or stepsrequired Hence, various simplifications are made in places that result in sub-opti-mal design and code

• The case study follows the same disclosure sequence as the chapters of the book.Every effort is made to ensure that technologies are not used before they are intro-duced Because of this, some parts of the design use alternative mechanisms that,again, can be sub-optimal

The following sections examine different aspects of the case study and the J2EE patternswithin it

Session Facades and Entity EJBs

Probably the most obvious use of a J2EE pattern in the case study are the SessionFacades that prevent the clients from accessing the entity EJBs directly This applies bothfor the standalone application clients and the servlets/JSPs All of the session beans inthe Agency (Advertise,AdvertiseJob, Agency, and Register) act in the role of SessionFacade because they all manipulate data in entity EJBs based on requests from theclients

An example of this relationship is shown in Figure 18.2 This figure shows the class tionships between an AdvertiseClient, its associated AdvertiseBean(the SessionFacade), and the CustomerBeanthat holds the back-end data The implementation of theCustomerBeanreflects the nature of this relationship because it only has a local homeinterface This means that the CustomerBeanis only intended for use by other EJBs such

rela-as the AdvertiseBean

F IGURE 18.2

The AdvertiseBean

acts as a Session Facade between the

AdvertiseClient and the CustomerBean

Trang 34

In terms of systemic qualities, the use of a Session Facade has the following impact:

• Maintainability and flexibility—By decoupling the client from the details of the

underlying data model, there is a large reduction in dependencies Fewer cies between layers make the system easier to change for maintenance reasons or

dependen-in the face of changdependen-ing requirements The dependen-introduction of the Session Facade vides an ideal place for the location of business logic that is separated from boththe client and the data management Any changes to the business logic or theunderlying data storage are then confined to the Session Facade and do not impactthe client code

pro-• Security—There is now one point of access for a particular piece of business logic

and its associated data Appropriate controls can be placed on the Session Facadethat are independent of the underlying data access control and properly reflect thelogic being undertaken

• Performance—In some ways, a Session Facade will reduce the level of

perfor-mance because extra code and method calls are introduced However, designing theSession Facade interface to offer a coarse-grained, business-oriented interface inplace of the underlying entity bean’s fine-grained, data-oriented interface can fre-quently offset any reduction in performance because it reduces the number ofremote method calls required to perform a task This type of interface simplifica-tion and business-orientation can be seen later when the use of a Value Object isdiscussed that reduces the number of remote method calls required to access andupdate a customer’s details

Before moving on, consider what you have just seen in terms of the general concept ofpatterns discussed at the start of this day’s material There are issues surrounding the use

of Entity EJBs directly from remote clients Most designers that have worked with EJBsfor some time know of these issues However, designers who are new to J2EE will notnecessarily identify these issues They may then produce poor quality systems until theylearn about such issues by trial and error By learning from such errors, the designerbecomes better at his or her job (designing J2EE applications) However, this is of littlesolace to the owner of the poor application on which the designer learned his or hertrade

If designers know of the existence of J2EE-oriented patterns catalogs, they can studythese as part of their J2EE education They would then learn about the issues surround-ing direct Entity EJB access from remote clients If they read the description of theSession Facade pattern, they would know that they could introduce a Session EJB asdescribed in this section This has the effect of making the systems they produce moremaintainable, flexible, and better performing The designers of the Agency application

Trang 35

have used the Session Facade pattern where appropriate Did they do this because theyhad learned from personal experience that direct Entity EJB access from distributedclients causes problems, or did they know this from studying J2EE patterns? To allintents and purposes it does not matter how they gained this J2EE design “wisdom,”what matters is that the delivered system is of higher quality than it would be without theapplication of this pattern By learning and applying the patterns described today, youshould be able to improve the quality of the J2EE applications on which you work.

Data Exchange and Value Objects

Within the Agency application, the Session bean data access methods return collections

of strings that identify jobs and other domain concepts The client then uses one of thesestrings to create another Session bean to retrieve the details associated with that job Analternative would be to use Value Objects to hold the information, such as job details,and to pass collections of these back and forth between the AgencySession bean and theclients

The question of whether, how, and where to apply Value Objects revolves around thestyle of the application and the amount of data passed When using an online catalog,such as those found in e-commerce applications, you will generally present the customerwith a list of products This list will be obtained as the result of some form of query (forexample, all the books by Ian Fleming—or even all the products sold that relate to JamesBond) The query results will be presented to the customer for him or her to make his orher choice To make this choice, the customer needs more information about the productthan just its name Additional information could include its type (is it a video of

GoldenEye, or a DVD, or a Playstation game, or a book?), the price, availability, and so

on This means that for every query result, you would want to pass back multiple pieces

of information In this case, encapsulating them in a Value Object would make a lot ofsense You could then return a collection of such Value Objects to the Web-tier client,which would then display them to the customer

The style of the Agency application is somewhat different from this Most of the mation presented to the user is “top-level” information, such as a list of customers orlocations Information is retrieved and updated as required Therefore, the applicationworks more on the principle of “browse and drill down,” meaning that the “next level” ofinformation (such as the details for a particular customer) is only fetched when requiredafter a selection has been made at the higher level Passing back collections of ValueObjects would be overkill in this situation because only one set of information (applicant

infor-or job) is required at any one time

Trang 36

However, the Value Object pattern can be applied to several of the agency EJB interfaces

Take, as an example, the Advertiseinterface (shown in Listing 18.1) that is used toupdate or retrieve information on a particular job advertiser Because the individual dataitems, such as the advertiser’s name, must be retrieved individually through calls to theSession EJB, the application displays excessive chattiness This means that there are lots

of network connections, each one retrieving a small amount of data This is in contrast tothe updateDetailsmethod that takes all of the advertiser’s details in a single methodcall You can apply the Value Object pattern to convert the repeated method calls into asingle method call that returns a single JavaBean This single JavaBean would contain all

of the required information

To show this pattern-based refactoring in practice, consider two forms of the Advertiseinterface The original Advertiseinterface is shown in Listing 18.1 and has one methodfor each property defined on the advertiser The interaction between the client and theSession EJB when loading the advertiser’s details is shown in Figure 18.3

L ISTING 18.1 Original Advertise Interface

1: public interface Advertise extends EJBObject 2: {

3: void updateDetails (String name, String email, String[] Address) 4: throws RemoteException;

5: String getLogin() throws RemoteException;

6: String getName() throws RemoteException;

7: String getEmail() throws RemoteException;

8: String[] getAddress() throws RemoteException;

9: String[] getJobs() throws RemoteException;

AdvertiseClient

«EJB»

AdvertiseBean

Get name loadDetails

Trang 37

Listing 18.2 shows a refactored interface containing a single query method for theadvertsiser’s details that returns a Value Object of type AdvertiseValueObject Theinteraction between the refactored client and Session EJB when loading details is shown

in Figure 18.4 As you can see, there are now only two remote method calls made duringthe load rather than four, thus reducing the chattiness of this part of the application Thischange will also approximately halve the time taken to load the details, because the timetaken to make the remote calls will generally dwarf the time spent in local processing.Note that you can now also use the Value Object as a parameter to updateDetailswhenupdating the advertiser’s details Although this change to the update does not improve net-work performance, it does mean that any changes to the information held per-advertiserneed only be made to the Value Object and the code that manipulates Value Objects ratherthan changing the Advertiseinterface

L ISTING 18.2 A Refactored Advertise Interface

1: public interface Advertise extends EJBObject 2: {

3: void updateDetails (AdvertiseValueObject details) throws RemoteException;

4: AdvertiseValueObject getDetails() throws RemoteException;

F IGURE 18.4

Interaction between the refactored

Trang 38

Listing 18.3 shows a possible implementation for the AdvertiseValueObject This is avery simple implementation and it would be quite possible to improve it, such as by pro-viding multiple constructors or allowing smarter addition of address information

However, the code shown is the minimum you would need Note that the Value Objectconforms to the rules for a JavaBean in that it has a no-argument constructor, it uses getter/setter naming, and it is declared as implementing Serializable

L ISTING 18.3 AdvertiseValueObject

1: public class AdvertiseValueObject implements java.io.Serializable 2: {

3: private String _login;

4: private String _name;

5: private String _email;

6: private String[] _address;

13: public void setName(String name) { _name = name; } 14: public String getEmail() { return _email; } 15: public void setEmail(String email) { _email = email; } 16: public String[] getAddress() { return _address; } 17: public void setAddress(String[] address) { _address = address; } 18: }

Using the AdvertiseValueObject, the code in the client (AdvertiseClient.java) thatloads the details would change to that shown in Listing 18.4 The code has changed verylittle, but the bulk of the data retrieval methods (apart from getDetailsand the getJobsmethod that is used in the loadJobsmethod) are now local rather than remote

L ISTING 18.4 Refactored loadDetails Method

1:

2: public class AdvertiseClient

3: { 4: .

5: private void loadDetails (Advertise advertise) throws RemoteException 6: {

7: AdvertiseValueObject details = advertise.getDetails();

Trang 39

One thing to note is that the list of jobs associated with the advertiser is not included inthe Value Object The client manipulates the jobs separately from the rest of the advertis-

er details Therefore, the updating and listing of jobs is kept separate from the tion of the advertiser’s details

manipula-In terms of systemic qualities, the use of a Value Object has the following impact:

• Performance—There is now one remote method call to retrieve applicant data

rather than five This will speed up the loading of the information by a sizeablefactor (providing that there are no other performance roadblocks anywhere else)

• Scalability—Fewer calls across the network will reduce the amount of network

bandwidth used and also the number of concurrent sockets required at each end ofthe connection This means that the solution is more scalable (resources run outless quickly)

• Maintainability and flexibility—The reduction in dependencies and coupling

brought about in the Registerinterface make subsequent changes to the applicantinformation easier to manage Although changes to the contents of the ValueObject will require changes in the client and server’s internal data and the databaseschema, there is no need to change the remote interface

There are also several variations on the Value Object pattern that you may find useful:

• Partial Value Object—If only part of the data held by the server is required by the

client, a Value Object can be used that encapsulates precisely the data required.This will reduce the overall amount of data passed over the network

• XML Value Object—You can extend the Value Object concept by passing an XML

document instead of a Java object This XML Value Object can be used to passdata between the presentation tier and the client tier Alternatively, the EJB inter-face can pass the XML document as a Stringfor easier interoperability withCORBA clients (see the CORBA discussion on Day 19, “Integrating with ExternalResources”)

Data Access Without Entity EJBs

When you first started to look at the use of EJBs in the case study, on Day 4,

“Introduction to EJBs,” and Day 5, “Session EJBs,” Entity EJBs were not yet used to

L ISTING 18.4 Continued

Trang 40

encapsulate the underlying data Entity EJBs are a fundamental part of the J2EE ture They provide an extra level of flexibility by abstracting the underlying data sourceand, if using CMP, remove the need to write JDBC code However, you may find thatthey do not bring any advantage for simpler, read-mostly applications In this case, youmay want to stick with direct database access from Session EJBs

architec-The Session EJBs from the Day 5 case study use direct database access for all queriesand updates Although direct database access is conceptually simpler than using an EntityEJB, it does mean that the data access code is intermingled with the business logic in theSession bean This has a negative impact on

• Maintainability—Changes to either the data access code or the business logic will

require that you change the Session bean code An incorrect update can potentiallydestabilize all of the functionality of the Session bean

• Flexibility—Should the underlying data source change, such intermingled code is

difficult to change This change could be anything from the use of a different base to a completely different data storage mechanism, such as LDAP, mainframe,

adapter between the

user and the specific

data source.

Oracle database

Client

OracleDAO

Sybase database SybaseDAO

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN