Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

J2EE Design Patterns

J2EE Design Patterns

Not surprisingly, the concept of design patterns originated in the world of architecture. A design pattern is a proven, reusable solution to a recurring problem.

I've always enjoyed building things, both as a software engineer and as a homeowner. Whether the raw materials are Java classes or plywood and nails, I get the best finished results when I start with a good design and follow standard procedures that reflect the experience and knowledge of seasoned professionals. When I wear my tool belt, I try to follow these "tricks of the trade." As a software developer, I use design patterns.

Software design patterns were initially popularized by the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. The four authors are often referred to as the "Gang of Four," or simply GOF.

Sun's Java Center has cataloged a number of design patterns specifically for J2EE applications (see http://java.sun.com/blueprints/corej2eepatterns). Each pattern is documented formally with accompanying UML diagrams. I'll introduce four of these patterns in this article.

Pattern #1: Composite View Pattern
Don't start from scratch. If you want to construct a housing development with a number of similar houses, you probably wouldn't undertake each house as a separate project. Instead, you would work from a master design and reuse common elements such as doors, windows, and floor plans. That's the idea behind this pattern.

Today's Web applications typically have complex screens with repeated elements such as menus, navigation bars, company logos, and so on. The Composite View pattern suggests that you divide the screens into pieces, coding the pieces as self-contained units. This pattern helps your Web application's screen to have a common look and feel, and it promotes reuse of view components.

It's easy to implement the Composite View pattern using JSPs. There are two built-in mechanisms: the <%@ include> directive and the <jsp:include> action. Both allow you to construct a JSP from a number of smaller JSPs (see Listing 1). Note that there is a subtle difference between JSP directives and JSP actions. Directives are acted upon when the JSP is translated to a servlet. This normally occurs just once during the lifetime of a Web application. JSP actions, however, are carried out at request time. Request-time inclusion gives you more flexibility and is generally the preferred approach.

A more sophisticated implementation of the Composite View pattern allows you to generate all of an application's screens dynamically, based on settings in an XML-based configuration file. One JSP can be used as a template that specifies the common overall layout and defines subregions that are filled in at run time. Some of these regions contain common screen elements, while other regions show content that varies according to the user's current activity. You will find this approach in Sun's demonstration J2EE application, the Java Pet Store (see http://java.sun.com/blueprints/patterns/ CompositeView.html).

Custom JSP tags are used to implement the Composite View pattern in the Pet Store application. Custom tags allow you to extend the JSP language and create your own tags. Each tag is associated with a Java class called the tag handler. Sun provides the JSP Standard Tag Library (JSTL), and BEA provides a set of custom tags that are packaged in a file called weblogic-tags.jar. This JAR file contains the tag handler classes and a tag library descriptor (TLD). To use these tags, copy this JAR file to the Web application that contains your JSPs and reference the tag library in the JSPs.

Pattern #2: Intercepting Filter Pattern
Tools that can be adapted with "snap-on" accessories are the most useful and flexible. If you've been in a hardware store lately, you've probably seen sets of tools that share a common battery pack. At one moment it's a drill, but with a quick twist of the wrist you can take off the drill head and turn it into a saw or a sander. This makes me think of the Intercepting Filter pattern, which involves creating pluggable filters that can intercept incoming HTTP requests and outgoing responses. You can add and remove these filters unobtrusively without any changes to existing code.

Servlet filters, introduced with servlet specification version 2.3, are perfect for this pattern. A servlet filter is a small class that allows you to manipulate the request and/or response. A filter object is instantiated and managed by the servlet container, and has a life cycle similar to a servlet. Common uses for filters include logging HTTP requests, validating request parameters, and authorizing or denying access to resources. A simple logging filter is shown in Listing 2. Filters can also be used to modify the response, changing its format and/or contents.

Filters are applied selectively to one or more servlets or JSPs by settings in web.xml (see Listing 3). Filters and filter mappings can also be configured in the WebLogic Administration Console by selecting your Web application and then clicking on the link labeled "Edit Web Application Deployment Descriptors."

Servlet filters provide a mechanism to encapsulate recurring tasks in reusable units, a goal shared by the Composite View and several other J2EE design patterns. Since filters are applied declaratively rather than programmatically, they can easily be enabled, disabled, or replaced, just like the attachments on my cordless drill.

Pattern #3: Session Facade Pattern
If you want to have a custom home built, you usually hire a general contractor, who then worries about dealing with all the various subcontractors (drywall, roofing, plumbing, and so on). This simplifies your life in that you only have to interface with and pay the general contractor. The general contractor serves as a front end, or "facade", for the subcontractors.

A commonly used J2EE pattern for EJBs is called the Session Facade pattern. In this pattern, a stateless session bean is used as a facade to hide access to one or more entity beans. Remote clients interact only with the session bean and never directly with the entity beans (see Figure 1). The first important benefit of the Session Facade pattern is that the client has a simpler interface and doesn't need to know about the details of which entity beans and which methods to use. In my analogy, the session bean is like the general contractor and the entity beans are the subcontractors.

The Session Facade pattern improves performance as only the calls between the client and the session bean go across the network, while calls from the session bean to the entity beans are local to the EJB container. Performance can be further enhanced through the use of local interfaces, introduced as part of the EJB specification version 2.0. Local interfaces provide support for "lightweight" access from within the EJB container, avoiding the overhead associated with a remote interface.

A third benefit of the Session Facade pattern relates to transactions. With container-managed transactions, the container begins a transaction when a method starts to execute and ends the transaction when the method returns. By enclosing the entity beans calls in the session bean method, the database operations are automatically grouped together as a transactional unit. To ensure that they participate in the same transaction, the entity bean methods should be assigned the "Required" transaction attribute in ejb-jar.xml (or by using the WebLogic Administration Console).

Pattern #4: Service Locator Pattern
Don't waste a lot of time looking for your tools. In an ideal world, if I needed my extra-long Phillips screwdriver, I would look for it just once and keep it close at hand until I finish my project. Unfortunately, I usually end up spending a lot of time looking for (and cursing at) the same tool. Distributed applications often exhibit the same behavior: they waste time looking for network resources. The Service Locator pattern solves this problem.

Most J2EE applications can take advantage of the Service Locator pattern. The idea behind this pattern is to provide a utility class that centralizes and hides all the details of a complex service. JNDI lookups are perfect candidates, since they generally need to be done only once, and the results can be saved for later use. Enterprise applications use JNDI lookups to locate EJB home interfaces, JDBC datasources, and Java Message Service (JMS) components.

Listing 4 shows a simple implementation of the Service Locator pattern. Note that the class does not offer a public constructor, but instead has a public static method that allows callers to access a unique instance of the class. This demonstrates a basic GOF pattern, the Singleton pattern.

We've looked at four J2EE design patterns, and I hope you'll be motivated to learn other patterns. I like to keep design patterns handy in my virtual "tool belt," and I always have room for more. In both software and home construction, design patterns help us to build better products and profit from the experience (and mistakes) of our colleagues. Now if I could just stop hitting my thumb with the hammer!

More Stories By Alan Baumgarten

Alan Baumgarten has over 20 years’ experience in software engineering and technical training. He currently teaches and develops courseware for /training/etc, Inc., a Columbia, MD– based firm specializing in software training for the enterprise. Alan holds a masters degree in computer science from The Johns Hopkins University.

[email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...