Concepts:
Web Application Frameworks Topics
- Introduction
- Model-View-Controller Design Pattern
- Struts
- JavaServer Faces
- Framework Selection Guidelines
- Complementary Technologies
- Resources
Introduction
Using an application framework presents many advantages during the implementation of a software application. A framework provides a reusable infrastructure that addresses many implementation details common across applications and helps avoid re-discovering and re-implementing solutions to common implementation problems. In addition, a framework often conforms to a programming model that represents an effective solution to the challenges of building a specific type of application. For Java 2 Enterprise Edition (J2EE) web applications, frameworks based on the Model-View-Controller (MVC) design pattern are considered best-of-breed, and among them, Struts has been the most popular. More recently, the J2EE standards committee released the JavaServer Faces (JSF) specification offering an MVC framework with additional benefits.
This document describes the benefits of the MVC design pattern and provides an overview of the Struts and JSF frameworks. It discusses their purpose, lists their advantages and disadvantages and provides guidelines on how to choose between them. Finally, it also discusses the integration of complementary technologies, namely, Service Data Objects (SDO) and Enterprise JavaBeans (EJB) into an architecture that uses these frameworks.
Model-View-Controller Design Pattern
Model-View-Controller (MVC) is a design pattern that separates an application's user interface from its business logic. It does so by layering the application's architecture into three parts: Model, View and Controller. Figure 1 shows the MVC architecture as applied to Web applications.
Figure 1: MVC Architecture for Web Applications
Model
The Model represents the state of the application and defines the business actions that modify it (persistent data and business logic). It can be inquired about its state (usually by the View) and be asked to change it (usually by the Controller). It knows nothing about the View or Controller.
View
The View provides the presentation of the Model. It represents the look of the application, that is, its user interface. It is responsible for presenting and collecting data to and from the user. The View can get the Model's state but cannot modify it.
Controller
The Controller reacts to user input and informs the Model to change its state accordingly. Specifically, it processes incoming user requests by dispatching them to the appropriate business logic functions (in the Model) and selecting the response to the user (the View) based on the outcome.
BenefitsThe MVC design pattern's separation of business logic from presentation results in the following benefits:
Enhanced Maintainability
Because the View and Model layers are decoupled, you can change the user interface without affecting the business rules and vice-versa. The impact of changes is, therefore, minimized.
Model Reusability
You can create multiple views of the same model. For example, if your application needs to support different client device types (for example, cell phones and PDAs), you can create new views specific to each technology and reuse the same model.
Separation of Responsibilities
Development roles can be separated allowing different members of the development team to focus on their area of expertise. Web Page designers, for instance, can be responsible for the View layer and work independently from Java developers who can concentrate on implementing the Controller and Model layers.
Struts
Struts is an application framework that allows the construction of dynamic Web applications using the MVC design pattern. It is a collection of cooperating Java classes, Servlets, and JavaServer Page (JSP) tag libraries that can be used as a foundation for building an MVC implementation of an application based on Sun's J2EE Model 2 architecture:
- The Controller layer is implemented by Servlets.
- The view is implemented using JSPs.
- The Model layer is typically implemented using JavaBeans or Enterprise JavaBeans.
Architecture
Figure 2 shows the implementation of the MVC architecture in Struts and the processing flow of a client request.
Figure 2: Struts MVC Architecture and Request Processing Flow
Controller Components
Struts' main Controller components consist of a Front Controller servlet, ActionServlet, and the ActionForm and Action classes.
- ActionServlet
The ActionServlet receives an HTTP request, invokes the requested actions on the Model and selects the next view to display. It is the core of the framework. One instance of the ActionServlet class receives all incoming requests. The ActionServlet sets the state of an ActionForm using corresponding fields from the HTTP request, optionally asks it to validate itself and passes it to a mapped Action. Requests are mapped to Actions using a configuration file (struts-config.xml).
- ActionForm
The ActionForm class represents the form data. The ActionServlet instance automatically populates its properties with values from the input form and passes it to the requested Action. The ActionForm is also used to hold dynamic data from the Model to be displayed by the View.
- Action
The Action class contains logic to call the Model layer. When executed by the ActionServlet, it invokes Model objects to perform the business logic, and then tells the ActionServlet Controller where to go next.
Model
Struts does not specify which technology to use for the Model. Most commonly, however, Model objects are implemented using simple JavaBeans or more powerful components such as Enterprise JavaBeans.
View
The View is typically implemented using JavaServer Pages to take advantage of the JSP Custom Tag libraries provided with the framework. The dynamic data to be displayed is retrieved from JavaBeans or instances of the ActionForm class created by the Controller layer. Custom tags are the primary mechanism for accessing this data.
Benefits
Struts is an open source framework supported by a strong developer community and whose standards are managed by the Apache Software Foundation's Jakarta project. It is an appealing choice because it is non-vendor specific and is supported in many development tools. In addition to being an MVC-based framework, Struts' other benefits include:
- Struts is HTTP-centric and hides the low-level details HTTP request processing.
- It is model neutral and allows the developer to choose which technology to use in the Model layer.
- Struts is highly configurable. XML configuration files are used to control the flow of the application, user input validation, and error handling.
- Struts supports internationalization/localization and does so through the use of standard Java ResourceBundles.
- Struts provides the following features which greatly enhance Reusability:
- A rich set of JSP Custom tag libraries to handle such common tasks as general bean manipulation, conditional and iteration logic and HTML rendering
- A Tiles sub-framework that allows the creation of reusable User Interface templates to control layout and promote a common look and feel
- Access to the JSP Standard Tag Library (JSTL) by means of Struts-Expression Language (EL) for additional code reuse
Limitations
Struts' limitations include:
- Struts' open source nature means that its support relies on the developer community.
- Struts has a "JSP mindset" as it is difficult to use a different technology for the View layer.
- Struts does not provide a user interface component and event-handling model to allow the building of rich Web user interfaces.
JavaServer Faces
JavaServer Faces (JSF) is an application framework that allows the construction of Java Web applications using a user-interface driven approach. The technology provides an infrastructure for building Web applications using a standard user interface component model that runs on the server. Its goal is to make Web application development easier by simplifying the programming model and promoting user interface-oriented, event-driven Web development.
Architecture
JSF is an MVC-based application framework. It provides a rich architecture for defining user interface components, managing their state on the server, and handling client-generated events. It also provides support for validating user input and controlling page navigation. Figure 3 shows the main components of the JSF architecture and depicts the processing flow of a client request.
Figure 3: JSF Component Architecture and Page Request Processing Flow
FacesServlet
The FacesServlet is the entry point for all requests for a JavaServer Faces page. It initializes the resources needed by the framework to control the page's lifecycle and, subsequently, invokes the page to process the request. It serves as a Front Controller to the application.
JavaServer Faces Page
A JavaServer Faces page is a JSP page which includes JavaServer Faces tags to express all user interface components it contains. Each component declares its value association with a Backing Bean property and specifies any event listeners, validators, and converters it requires. The framework will automatically synchronize a component's data with a bound property in its associated Backing Bean.
User Interface Component Tree
The user interface components in the JSF page are represented on the server by a component tree (also called a "View"). When a request is processed by the framework, this tree is either created (for an initial page request) or restored from its saved state (for subsequent page requests).
Validator
A Validator is used to validate user input. JSF includes many standard validator classes and supports the creation of custom ones.
Backing Bean
A Backing Bean is a JavaBean that holds the data for a JSF Page's user interface components and implements methods that support their behavior. These methods typically include logic to perform event handling, validation, and navigation control. A Backing Bean usually invokes methods from a model object to perform business logic. JSF allows you to declare all the Backing Beans used by the page in the Faces configuration file (face-config.xml) so that they will be automatically instantiated by the Web container at application startup time (these beans are called Managed Beans). The configuration file also specifies the page navigation rules that work in conjunction with navigation control logic in Backing Beans.
Event Listener
An Event Listener is a user-defined class designed to handle a specific type of component generated event. JSF supports three types of events: value-changed events (e.g., user changed a component's value), action events (e.g., user clicked on a button) and data-model events (user selects a new row in a data set).
Renderer Kit
A Renderer Kit is a group of Renderers for a particular client type. A Renderer is a class that produces the appropriate output to display a user interface component on a specific client device. JSF provides a standard HTML render kit which generates HTML for component display and allows you to build your own render kit for other client types.
Converter
A Converter is used to translate an object to string for display and from string to an object for processing. It is also used to apply formatting and localization choices.
Benefits
JSF is a standards-based framework developed through the Java Community Process (JCP) and will be made part of future releases of the Java 2 Enterprise Edition (J2EE) specification. As such, it establishes the official standard for building Java server-side user interfaces. Its major strengths include a simplified programming model which allows developers to build Web applications with reduced effort and a flexible architecture which cleanly separates application logic from presentation (by virtue of its MVC nature). The following benefits derive from these strengths:
- Rapid Application Development
JSF enables the rapid development of Web applications through its simplified programming model. Developers can easily assemble reusable user interface components in a page, connect them to application data sources and wire client-generated events to server-side event handlers. The framework take cares of automatically synchronizing component state and provides comprehensive support for common Web programming tasks such as validating user input, executing business logic and controlling page navigation. Also, more and more vendors are providing tool support for building Web user interfaces using JSF in a visual way to further enhance productivity.
- Maintainability
JSF's clean separation of presentation and behavior at the user interface component level results in a separation of concerns and improved maintainability at a fine-grained level:
o A Page Designer can focus using a tag to display a component while a Java developer implements its behavior. When finished, they can quickly link the pieces using JSF's simple programming model.
o Changes to the presentation of a component do not affect its behavior. You can, for example, select a new tag to display a component without needing to change the code "behind it".
- Flexibility
JSF does not limit you to a particular presentation technology or markup language:
o JSF's flexible Rendering model allows components to be client device independent. Components can be displayed in ways other than HTML by using renderers that generate a different markup language. The same component logic can, therefore, be reused for multiple client types using different renderers.
o JSF provides a JSP custom tag library to represent components on a JSP page, but also allows you to use a presentation technology other that JSP. This is possible because JSF technology is directly layered on top of the Servlet API.
- Extensibility
JSF's User Interface Component model can be extended to create custom components. This allows you to create sophisticated components such as trees and menus and build richer and more user-friendly user interfaces for your Web applications.
Limitations
JSF's limitations include:
- It is a new technology that will continue to improve over time.
- JSF has no layout management features to promote consistent look and feel and allow a page to be divided into individually processed sections.
- JSF development is difficult when done by hand without tool support. Its RAD benefits are truly realized when using an IDE with visual design tools.
Framework Selection Guide
As a best practice, you should use an application framework that conforms to the MVC architecture. Both Struts and JSF do so and, therefore, constitute good choices. When comparing them, however, it becomes apparent that both have overlapping functionality. For example, they both provide support for input validation, request processing, and page navigation. How do you choose between the two? Table 1 lists important framework features and compares how Struts and JSF supports them. You can use it as a guide to help make a decision based on the features you need and what framework supports them best.
Struts JavaServer Faces Programming Model
- Form processing Style
- Event-driven Style
UI Components and Support
- Simple UI components provided in Struts-HTML tag library
- Data binding to ActionForm bean provided
- Rich UI components
- Additional Custom Components can be created
- Data binding to Backing Beans or any Model object supported
- Event handling support provided
Client Device Independence
- Not Supported
- Render Kits provide device independence
Error Handling and Validation
- Validation framework driven by an XML file (validation.xml)
- Validation framework with many predefined validators
- Custom validators can be created
Scripting
- Scripts written in Java Action classes
- Scripts have access to form data only
- Scripts written in Backing beans, Model classes or Event Listener classes
- Scripts can be attached to events
- Scripts can access UI components and their data
Page Flow
- Sophisticated, flexible framework
- XML file based
- Sophisticated, flexible framework
- Configured in an XML file (faces-config.xml)
Session and object state Management
- Manual
- Automatic
Table 1: Comparison of Struts and JSF Features
Note also that the decision does not have to be an either/or choice. You can also combine both technologies using a Struts-Faces integration library developed by the Apache project (see
Resources
). This library allows you to use JSF components in your Web user interface along with Struts controller components, actions, and business logic.In the long run, the recommendation is to use JSF for new projects and to migrate existing Struts projects to JSF. The rationale behind this can be summarized as follows:
- JSF brings the richness to Web user interfaces that users have long been waiting for and which Struts does not provide.
- JSF's simple programming model provides a high level of abstraction, which enhances productivity. It allows you to think in terms of user interface components and client events as opposed to basic "form and field" processing in Struts.
- JSF provides a complete solution for building Web applications and integrates easily with new technologies such as Service Data Objects (see
Complementary Technologies
).- Powerful Integrated Development Environments (IDEs), such as RAD 6.0, already support JSF today.
- JSF's future inclusion in J2EE specification will result in widespread tool support from many vendors.
Complementary Technologies
This section looks at how the following technologies can be integrated into a Struts or JSF framework to produce a powerful and complete end-to-end implementation solution: Service Data Objects (SDOs) and Enterprise JavaBeans (EJBs).
For a description of the EJB technology, see Guidelines: Enterprise JavaBean (EJB)
Service Data Objects
Service Data Objects is a specification for a programming model that allows access to back-end data in a uniform, data source independent and disconnected way. The model allows data to be retrieved from any type of data source (Relational Database, EJB Entity Beans, Web Service, XML data source, and so forth) and presented uniformly as a structured graph of data (DataGraph). SDO provides for disconnected operations by allowing the retrieval of the DataGraph to be independent of any back-end connections or transactions. It is still a proposed specification submitted through the JCP as Java Specification Request (JSR) 235.
Architecture
The SDO architecture uses a uniform data access layer (Data Mediator Service) to return DataGraphs to clients from heterogeneous data sources. Figure 4 shows the components of the SDO architecture.
Figure 4: SDO Architecture
DataObject
A DataObject holds actual data (for example, primitive values or row of data from a relational database) and possible references to other DataObjects. It can be introspected to determine its type, relationships, and constraints.
DataGraph
A DataGraph holds a set of DataObjects and typically represents the unit of transfer between components in the architecture. It records all changes to data, including new, changed or deleted Data Objects.
Data Mediator Service
A Data Mediator Service is responsible for interacting with a Data Source to produce DataGraphs representing the data. Native data representation is converted to the SDO graphical representation by this pluggable service. The Mediator is also responsible for applying changes in a DataGraph back to the Data Source.
LFramework Applicability
SDO technology promises easy tool and framework integration. In the context of JSF and other MVC frameworks, the following two solutions can be considered:
Binding from UI component to SDO (JSF)
In a JSF framework, values for Web user interface components can be declaratively bound to SDOs for data retrieval purposes. For example, a Data Table component could be bound to an SDO for retrieval of its values from a back-end data source. This combination makes data connectivity from a UI component easy with no programming required. Figure 5 shows the resulting architecture of binding JSF UI components to SDOs.
Figure 5: Using SDOs with JSF
Model object to SDO (any MVC framework)
The model layer of an MVC framework could use SDOs to access back-end data. Figure 6 shows an example of a model client using SDOs to access data persisted using Entity EJBs. The model object uses DataGraphs returned by a Stateless Session EJB façade. This Session bean façade, in turn, retrieves the DataGraphs from the Mediator, which acts as a data façade for the Entity EJB based persistence mechanism.
Figure 6: Using SDOs with Model objects and EJBs
Resources
The following links provide additional information related to the application frameworks and component technologies discussed in this document:
- Struts Documentation: http://jakarta.apache.org/struts/index.html
- JavaServerFaces Documentation: http://java.sun.com/j2ee/javaserverfaces
- Struts-Faces Integration Library: http://cvs.apache.org/builds/jakarta-struts/nightly/struts-faces/
- Service Data Objects White Paper: ftp://www6.software.ibm.com/software/developer/library/j-commonj-sdowmt/Next-Gen-Data-Programming-Whitepaper.doc (download MS-Word)
- Developing JSF Applications using WebSphere Studio V5.1.1:
http://www-106.ibm.com/developerworks/websphere/techjournal/0401_barcia/barcia.html
Rational Unified Process