Welcome!

Java IoT Authors: Yeshim Deniz, Pat Romanski, Liz McMillan, Zakia Bouachraoui, Carmen Gonzalez

Related Topics: Java IoT

Java IoT: Article

Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate

Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate

JavaServer Faces (JSF) technology is a new user interface framework for J2EE applications. This article uses the familiar Pet Store application to demonstrate how to build a real-world Web application using JSF, the Spring Framework, and Hibernate. Since JSF is a new technology, this article will concentrate on the use of JSF. It presents several advanced features in JSF development, including Tiles integration and business logic-tier integration.

Java Pet Store
The Java Pet Store is a sample application from the Java Enterprise BluePrints program. It documents best practices, design patterns, and architectural ideas for J2EE applications.

MyPetStore, the sample application for this article, is a reimplementation of the Java Pet Store using JSF, Spring, and Hibernate.

I won't be able to cover all the features of the Pet Store in one article. MyPetStore allows a user to browse through a catalog and purchase pets using a shopping cart. Figure 1 provides the page-flow diagram.

JSF
JSF is a server-side, user interface component framework for J2EE applications. JSF contains an API that represents UI components and manages their states; handles events, server-side validation, and data conversion; defines page navigation; supports internationalization; and provides extensibility for all these features. It also contains two JSP (JavaServer Pages) custom tag libraries, HTML and Core, for expressing UI components within a JSP page and wiring components to server-side objects.

JSF is not just another Web framework. It's particularly suited, by design, for use with applications based on the MVC (Model-View-Controller) architecture. The Swing-like object-oriented Web application development, the bean management facility, an extensible UI component model, the flexible rendering model, and the extensible conversion and validation model are the unique features that differentiate JSF from other Web frameworks.

Despite its strength, JSF is not mature at its current stage. Components, converters, and validators that ship with JSF are basic. The per-component validation model cannot handle many-to-many validation between components and validators. In addition, JSF custom tags cannot integrate with JSTL (JSP Standard Tag Library) seamlessly.

High-Level Architecture
MyPetStore uses a multitiered nondistributed architecture. For a multitiered architecture, the functionalities of an application are partitioned into different tiers, e.g., presentation, business logic, integration, etc. Well-defined interfaces isolate each tier's responsibility. A nondistributed architecture means that all the tiers are physically located in the same application server. Figure 2 shows you the high-level architecture of MyPetStore.

JSF is used in the presentation tier to collect and validate user input, present data, control page navigation, and delegate user input to the business-logic tier. Tiles is used to manage the layout of the application.

Spring is used to implement the business-logic tier. The architectural basis of Spring is an Inversion of Control (IOC) container based around the use of JavaBean properties. Spring is a layered application framework that can be leveraged at many levels. It contains a set of loosely coupled subframeworks. The use of the bean factory, application context, declarative transaction management, and Hibernate integration are demonstrated in this application.

The integration tier is implemented with the open source O/R (object/relational) mapping framework - Hibernate. Hibernate relieves us of low-level JDBC coding. It's less invasive than other O/R mapping frameworks, such as JDO and CocoBase. Rather than utilize bytecode processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which describes persistent fields and associations, as well as any subclasses or proxies of the persistent object. The compilation of the mapping documents and SQL generation occurs at system startup time.

The combination of the business logic tier and the integration tier can also be referred to as the middle tier.

The integration between different tiers is not a trivial task. MyPetStore demonstrates how to use the JSF bean management facility and ServiceLocator pattern to integrate JSF with the business logic tier. By using Spring, the business logic tier and integration tier can be wired up easily.

Implementation
Now, let's go through the implementation details, tier by tier, of the UpdateShoppingCart, the most important and complex use case in this application.

Presentation Tier
The presentation tier tasks include creating and registering the backing beans (explained later), writing JSP pages, defining navigation rules, integrating with Tiles, and integrating with the middle tier. Our shopping cart screen looks like Figure 3.

Backing Bean
Backing bean is a JSF-specific term. A backing bean defines the properties and handling logic associated with the UI components used on a JSF page. Each backing bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that performs functions for the component.

Let's create a backing bean - CartBean - that contains not only the properties maps to the data for the UI components on the page, but also three actions: addItemAction, removeItemAction, and updateAction. Because the JSF bean management facility is based on Java reflection, our backing bean does not need to implement any interface. Listing 1 provides the code segment of the CartBean.

The CartBean contains a reference to a Cart business object. The Cart business object contains all the shopping cart-related data and business logic (the Cart class will be discussed later). This approach, to include the business object directly inside the backing bean, is simple and efficient. However, it tightly couples the backing bean with the back-end business object. Another approach is to decouple the backing bean and the business object. The drawback of this approach is that mapping has to be performed between the objects. Data needs to be copied between the backing bean and the business object.

There's no business logic inside the backing bean actions. The backing bean action simply delegates the user request to the middle tier. The addItemAction takes the item ID from the request, then it looks up the CatalogService through the ServiceLocator and gets the item associated with the item ID. It calls the addItem method on the Cart business object. The business logic of how to add an item to the cart is handled by the Cart business object. Finally, if everything succeeds, the navigation result of success is returned to the JSF implementation.

Backing Bean Registration
To let the JSF bean management facility manage your backing bean, the CartBean must be registered in the JSF configuration resource file faces-managed-beans.xml (see Listing 2).

The CartBean is set to have a scope of a session, which means the JSF implementation creates a CartBean instance if it is referenced inside any JSP page for the first time during a session. The CartBean instance is kept under the session scope. This way the user can interact with the stateful shopping cart, add an item, remove an item, update the cart, and finally check out.

The JSP Page
The cart.jsp is the page to present the content of a shopping cart. It contains UI components and wires the components to the CartBean (see Listing 3).

The page starts out with the tag library declarations. The JSF implementation defines two sets of tags. The core tags are independent of the rendering technology and are defined under prefix f. The HTML tags generate HTML-specific markup and are defined under prefix h. All JSF tags should be contained inside an f:view or f:subview tag.

h:outputText is used to present a message to the user once the shopping cart is empty:

 


<h:outputText value="Your Shopping Cart is Empty"
  styleClass="title" rendered="#{cartBean.numberOfItems <= 0}"/>

The rendered attribute takes a boolean variable. If the value is false, the h:outputText will not be rendered. The rendered attribute can give you the same effect as a JSTL c:if. Since JSF and JSTL are not integrated well, it's good practice to try not to mix them together.

h:dataTable is used to iterate through the items inside the shopping cart and present them inside a HTML table. The value attribute

 


 value="#{cartBean.cartItemList}"

represents the list data over which h:dataTable iterates. The name of each individual item is specified through the var attribute. You can control the presentation style of each individual column through the columnClasses attribute.

Inside h:dataTable, h:inputText is used to take user input - the quantity of the current item:

 


<h:inputText value="#{cartItem.quantity}" size="5"/>

The attribute value="#{cartItem.quantity}" tells the JSF implementation to link the text field with the quantity property of the cart item. When the page is displayed, the getQuantity method is called to obtain the current property value. When the page is submitted, the setQuantity method is invoked to set the value that the user enters.

h:commandButton is used to create the "Update Cart" button, which allows the user to update the shopping cart. The action attribute action="#{cartBean.updateAction}" contains a method-binding expression and tells the JSF implementation to invoke the updateAction method on the CartBean inside the session scope. The updateAction returns a navigation result, which determines the next page to go to.

The Check Out link is implemented with h:outputLink, which generates an HTML anchor element. Once the user clicks the link, it takes the user to the createOrder page.

Navigation
Navigation is one of the key features provided by JSF. For this application, all navigation rules are defined inside the faces-navigation.xml. There are two navigation rules related to the current use case. Here's the definition of the first rule:

 


<navigation-rule>
  <from-view-id>/cart.jsp</from-view-id>
  <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/cart.jsp</to-view-id>
  </navigation-case>
</navigation-rule>

This rule tells the JSF implementation that from the cart.jsp, if any action finishes successfully and returns success, the cart.jsp will be refreshed to reflect the current state of the shopping cart. The second rule is about error handling and is defined as a global navigation rule. It's not discussed here. Please refer to the faces-navigation.xml for detailed information.

Integration with Tiles
Tiles is a framework that makes using template layouts much easier through the use of a simple but effective tag library. Tiles separates the layout from content, makes your Web application easier to maintain, and keeps a common look and feel among all the pages. JSF and Tiles are a powerful combination.

JSF does not have built-in Tiles support. Tiles definitions cannot be referenced directly inside JSF applications. MyPetStore uses a workaround to integrate Tiles with JSF successfully. Tiles definition is referenced by JSF indirectly through a separate wrapper JSP file. The drawback of this approach is to have two JSP pages for each logical view. One is the content tile and the other is the wrapper JSP page with the Tiles definition. A tile is used to describe a page region managed by the Tiles framework. A tile can contain other tiles.

Here are step-by-step instructions on how to integrate JSF with Tiles:

  • Put struts.jar under your application's classpath (Tiles is bundled with Struts1.2).
  • Enable Tiles inside web.xml (see Listing 4). (Listings 4-10 can be downloaded from www.sys-con.com/java/sourcec.cfm.)
  • Build the layout template. The layout of MyPetStore is defined inside layout.jsp (see Listing 5). This template controls the layout of the entire application. Tiles custom tag <tiles:insert attribute="sider" flush="false"/> tells the Tiles framework to insert the tile identified by the value of the specified attribute.
  • Write the base Tiles definition. A Tiles definition allows you to specify the attributes that are used by a layout template. Tiles supports definition inheritance. You can declare a base definition and then create other definitions derived from that base. In MyPetStore, a base Tiles definition is defined inside the tiles.xml (see Listing 6). The base Tiles definition uses layout.jsp as the layout template and defines the common tiles used throughout the application, e.g., header, footer, etc.
  • Write the wrapper JSP page. All the tiles with the real content are defined inside the Tiles directory. For each logical view, there's a wrapper JSP page. Here's the wrapper JSP page for cart.jsp:

 


<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
<tiles:insert definition=".mainLayout">
  <tiles:put name="title" value="Shopping Cart Page"/>
  <tiles:put name="body" value="/tiles/cart.jsp"/>
</tiles:insert>

It tells the Tiles framework to insert the content tile /tiles/cart.jsp into the body part of the page defined by the base Tiles definition .mainLayout.

Integration with the Business Logic Tier
The ServiceLocator pattern and the JSF bean management facility are used to integrate the JSF-based presentation tier with the business logic tier. The ServiceLocator abstracts the logic that looks for services. In this application, ServiceLocator is defined as an interface and implemented as a JSF managed bean, ServiceLocatorBean. The ServiceLocatorBean looks up the services from the Spring application context:

 


ServletContext context = FacesUtils.getServletContext();
this.appContext =
  WebApplicationContextUtils.getRequiredWebApplicationContext(context);
this.catalogService = 
  (CatalogService)this.lookupService(CATALOG_SERVICE_BEAN_NAME);
...

The ServiceLocator is defined as a property inside the BaseBean. The JSF bean management facility wires the ServiceLocator implementation with those managed beans that need to access the middle tier.

 


<managed-property>
  <property-name>serviceLocator</property-name>
  <value>#{serviceLocatorBean}</value>
</managed-property>

IOC is used here.

Middle Tier
The tasks in this tier consist of defining the business objects with their mappings, creating the service interfaces with their implementations, implementing the DAOs (data access object), and wiring the objects.

The Business Object
The Cart business object is implemented as a POJO (plain old Java object) (see Listing 7). It contains the data associated with a shopping cart; it also contains actions with business logic, e.g., addItem, getSubTotal, etc.

The Business Service
The CatalogService interface defines all of the catalog management-related services:

 


public interface CatalogService {
  public List getCategoryList() throws MyPetStoreException;
  public Category getCategory(String categoryId)
    throws MyPetStoreException;

  ...
}

Spring Configuration
Listing 8 provides the CatalogService's Spring configuration inside applicationContext.xml.

The Spring declarative transaction management is set up for the CatalogService. Spring bean factory creates and manages a CatalogService singleton object. By using Spring bean factory, the need for customized bean factories is eliminated.

The CatalogServiceImpl is the implementation of the CatalogService, which contains a setter for the CatalogDao. The CatalogDao is defined as an interface and its default implementation is the CatalogDaoHibernateImpl. Spring wires the CatalogServiceImpl with the CatalogDao. Because we are coding to interfaces, we don't tightly couple the implementations. For example, by changing the Spring applicationContext.xml, we can tie the CatalogServiceImpl with a different CatalogDao implementation - Catalog-DaoJDOImpl.

Integration with Hibernate
Listing 9 provides the HibernateSessionFactory's configuration. CatalogDao uses the HibernateTemplate to integrate Spring with Hibernate. Here's the configuration for HibernateTemplate:

 


<bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate.HibernateTemplate">
  <property name="sessionFactory">
    <ref bean="sessionFactory"/>
 		</property> <property name="jdbcExceptionTranslator">
    <ref bean="jdbcExceptionTranslator"/>
  </property>
</bean>

Hibernate maps business objects to the relational database using XML configuration files. Item.hbm.xml expresses the mapping for the Item business object. The configuration files are in the same directory as the corresponding business objects. Listing 10 provides the Item.hbm.xml. Hibernate maintains the relationship between objects. The mapping definition defines a many-to-one relationship between Item and Product.

Finally, CatalogDao is wired with HibernateTemplate by Spring:

 


<bean id="catalogDao"
  class="mypetstore.model.dao.hibernate.CatalogDaoHibernateImpl">
  <property name="hibernateTemplate">
    <ref bean="hibernateTemplate"/>
  </property>
</bean>

End-to-End
Figure 4 demonstrates the end-to-end integration of all the tiers for AddItemToCart: a sub-use case of the UpdateShoppingCart use case.

Technologies and JSF Features Matrix
The UpdateShoppingCart use case doesn't cover all the technologies and advanced JSF features we used in this application, e.g., security, pagination, etc. Table 1 can serve as a reference catalog to help you understand this application.

Configuration and Installation
You can download the source code for MyPetStore from www.sys-con.com/java/sourcec.cfm.

The Package Structure
After unzipping the code, you should see the following directory structure:

 


mypetstore
  /bin
  /docs
  /lib
  /src
  /web
    /images
    /tiles
    /WEB-INF
  build.xml

Table 2 explains each part of the directory structure.

System Requirements
You'll need the following tools to build and run the MyPetStore application:

  • JDK 1.4.2 or later
  • Ant
  • Tomcat 5.x
  • MySQL 4.x

Installation Instructions

  • Prepare the database. Run bin/mypetstore.sql against MySQL to build database schema and load seed data. If you'd like to use another RDBMS, this script may need to be modified.
  • Change the configuration (optional for default MySQL installation).
    - Find and open web/WEB-INF/applicationContext.xml.
    - Under the definition of the datasource bean, modify the JDBC connection properties (URL, username, password) to match the database you're using.
    - Save the file.
  • Build the Web application by Ant (the default target is build.war).
  • Copy the dist/mypetstore.war to the <tomcat-home>/webapps directory.
  • Start Tomcat.

For the default Tomcat installation, MyPetStore is accessible from http://localhost:8080/mypetstore

Log on to the application using j2ee as the username and password.

Summary
In this article I tried to provide a picture of how you can integrate JSF, Tiles, Spring, and Hibernate in one application. With minimum theory, you should now be able to start building such typical Web applications as a pet store. If I sparked your interest in studying any of these technologies, my mission was accomplished.

Resources

  • JavaServer Faces: http://java.sun.com/j2ee/javaserverfaces
  • Tiles (bundled with Struts1.2): http://struts.apache.org
  • The Spring Framework: http://springframework.org
  • Hibernate: http://hibernate.org
  • MySQL: http://mysql.com/
  • Tomcat: http://jakarta.apache.org/tomcat/
  • Java Pet Store: http://java.sun.com/developer/releases/petstore
  • Johnson, R. (2002). Expert One-on-One J2EE Design and Development (Programmer to Programmer). Wrox.
  • Singh, I., et al, (2002). Designing Enterprise Applications with the J2EE Platform. Addison-Wesley Professional.
  • More Stories By Derek Yang Shen

    Derek is a senior software engineer at Overture Services, Inc., in
    Pasadena, California. Derek is a Sun Certified Enterprise Architect and has
    been working with J2EE exclusively for the past five years. He holds an
    MS in computer science from UCLA.

    Comments (24)

    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.


    IoT & Smart Cities Stories
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    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...
    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...
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    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 settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
    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...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...