Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 75 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
75
Dung lượng
8,01 MB
Nội dung
In the following sections, we discuss the basic object structure of Web MVC frameworks (see Figure 5.4). This architecture is implemented by many of the previously mentioned frameworks. 124 CHAPTER 5 • Web Application Architecture and Design Model JSP Page Controller Action <<web>> Input Controller Output Controller <<wap>> Input Controller Web Service Controller JSP XML Input Controller Application Controller Business Logic http wap Figure 5.4 MVC for the Web Input Controller The input controller is a central feature. There is a single input controller for all pages in a Web application. The input controller parses input, determines the parameter-passing mechanisms, extracts any necessary information from the request, cooperates with the application controller to determine the next opera- tion (typically called an action), and invokes that action in the correct context. By having a single component as an input controller, any knowledge of HTTP or naming conventions is localized at the request level. This reduces the amount of code duplication and the total size of code. This also makes it easier to modify any of the input processing functions because there is a single point of modifica- tion. Note that the input controller component is typically a servlet, and there may be one instance for accessing the applications over HTTP via a regular Web browser and another instance for mobile applications using a Wireless Application Protocol (WAP) enabled device. Application Controller The application controller is typically a regular Java object. It coordinates logic related to the application flow, handles errors, maintains longer-term state (includ- ing references to the business objects), and determines which view to display. The application controller needs to understand requests, and how they participate in the organized flow of the application, and forward these requests to the planned responses. Web requests are HTTP encoded, string, and string-based key-value pairs. Application controllers typically need a mapping of these input keys to the application objects that manage the flow. Most frameworks maintain these map- pings in complex XML configuration files, such as the struts-config.xml file used in Struts. For example, URI sequences like the following are known by the input controller, /leagueplanet/addPlayer.do This relies on a naming convention, with the disadvantages described earlier, but because this is the only component used in this way, the impact is minimized. In a better design, a single application controller is typically responsible for mul- tiple Web pages and activities. In a simple application, a single application con- troller might be responsible for all pages. In a complex application, there are typically multiple application controllers for the different areas of the applica- tion. By using a single, well-encapsulated object as the central point of reference for encapsulating information, the application controller resolves the issues of information hiding and naming conventions. Rather than storing isolated pieces of information in the session, the information can be stored in business objects and accessed using messages from the application controller. Programming lan- guage mechanisms let you track the use of the application controller and busi- ness objects, making it easier for you to modify your code. You also get static type checking as an additional validation of data usage. There are several designs for application controllers. The Struts framework refers to them as actions while JSF calls them managed backing beans. In Struts there can be many actions. For example, if your application has two use cases that support creating teams and adding players to these teams, you may perform these using two corresponding actions. The program listing in Example 5.2 is a summary of how these action classes might look in a Struts application. Example 5.2 Struts Action Class Example Code public class CreateTeamAction { public void execute( ){} } Web Applications 125 public class AddPlayerAction { public void execute( ){} } Clearly, these team and player actions are related. For example, you add players to teams. However, Struts does not have a mechanism to group the actions. For example, multiple actions that are a part of the same flow, like an online registration process, cannot be grouped. This shortcoming in Struts is addressed by other Struts-based frameworks, such as the Eclipse Pollinate project, where the application controller is a Java object called the page flow. The page flow is a class that encapsulates a group of actions as methods and defines a structure for describing the flow between them. In Pollinate, you would have implemented the same use case using a single page flow class. The action classes and their behavior shown in Example 5.2 would have been implemented as methods in a page flow. The program listing in Example 5.3 demonstrates the ability to group actions and associate them with an object, such as the page flow. Having an application controller for a related group of actions increases your ability to express the appli- cation logic. Additionally, you can maintain state for this flow in an object rather than using HTTP specific request and session APIs. Example 5.3 Page Flow Class Example Code public class LeaguePlanetPageFlow extends PageFlowController { public Forward createTeam(){ } public Forward addPlayer(){ } } The two most popular MVC implementations for Java Web applications, Struts and JSF, are very similar in concept. Some claim that JSF is closer to MVC than Struts due to the availability of a rich stateful component set at the view layer and support for an event-based model to manage controller interactions (e.g., button-clicked events). JSF also provides an extensive standard tag library to reduce the amount of Java code in JSPs (see Example 5.4). Example 5.4 JSF JSP Tags <h:panelGroup> <h:commandButton id="submitCreateTeam" action="#{JsfLeaguePlanetBean.createTeam}" value="Create Team" /> <h:commandButton id="submitAddPlayer" action="#{JsfLeaguePlanetBean.addPlayer}" value="Add Player" /> </h:panelGroup> 126 CHAPTER 5 • Web Application Architecture and Design However, one must always keep in mind that these frameworks exist on top of the stateless HTTP protocol. JSF has the concept of an application controller in the form of managed backing beans (see Example 5.5). These beans can encapsulate a group of related activities, a capability that Struts lacks. Finally, the concept of page flow does not exist in either JSF or Struts. This information is implicit in the controllers and XML-based configuration files. Example 5.5 JSF-Managed Backing Bean public class JsfLeaguePlanetBean { public String createTeam( ){} public String addPlayer( ){} } The input controller will invoke one of many possible actions on each request. One of its responsibilities is to determine the correct action to invoke. This deci- sion depends on both the input from the client and the application’s current state, so it is determined by the application controller. We represent the result of this determination as the ApplicationController object (ApplicationController is an implementation of the Command pattern described in [Gamma1995]). Business objects are plain Java objects that contain only business logic. They should have no knowledge of any other layers. The application controller is the only component that manipulates the business objects (see Figure 5.4 earlier). These char- acteristics make it much easier to develop and test the business logic in isolation from the Web infrastructure. If the application is designed properly, the business objects are isolated, allowing you to use the same implementation for a thin-client Web application, a more rich-client implementation, or even a traditional desktop UI. View In a J2EE application, views are typically JSPs that can access the application controller and business objects. Views should contain as little code as possible, delegating most functionality to the application controller or business objects. Only code directly related to presentation in the current page should be used in a page. The JSP specification also defines tag libraries (taglibs) for defining cus- tomized JSP tags that encapsulate complex view layer behavior. It is preferable to use taglibs to create custom tags to remove complex code from the pages alto- gether. Figure 5.4 (earlier) shows two different view mechanisms. The JSP Page Controller uses a JSP implementation appropriate for a Web browser or WAP device. The Web Service Controller responds to the same request and produces an XML response suitable for consumption by other applications, such as a .NET system, or a rich-client application. Web Applications 127 128 CHAPTER 5 • Web Application Architecture and Design beans beehive beehive Presentation Struts jsf mvc jsf beehive Business Logic beehive Data dao beehive beehive beans Figure 5.5 Java Application Framework OSGi The OSGi Alliance (formerly the Open Services Gateway Initiative) defines a standard for providing Java-based service platforms. The specification defines a framework for an application life cycle model and a service registry. OSGi implementations such as Eclipse Equinox, Felix, and Knoplerfish provide com- plete and dynamic component models, something that has been missing in standard Java runtime environments. This means applications or components, which are called OSGi bundles, can be installed, started, stopped, updated and uninstalled, even remotely, without requiring a reboot. Java Application Frameworks There are a number of Open Source Java frameworks that help implement Web application best practices. In this section we’ll quickly review some of them (see Figure 5.5). These frameworks simplify development of Java Web applica- tions. They provide capabilities that improve the testability and maintainability of the code and simplify development. They separate architectural concerns and integrate well with application servers. Apache Beehive The Beehive project provides a framework for lightweight, metadata-driven components that reduce the coding necessary for J2EE. Beehive addresses all three layers of Web applications. The framework is based on annotations, partic- ularly JSR 175 metadata [JSR175]. It uses other Apache projects such as Struts and Axis. It has NetUI for presentation, Controls framework for lightweight components and Web Service Metadata (WSM), an implementation of JSR 181, and an annotation-driven model for building Java Web services [JSR181]. Apache Struts Apache Struts is a framework to provide a control layer based on standard Java Web technologies, like JSPs and servlets, and other Apache projects. It is a varia- tion of the MVC design pattern. JavaServer Faces JSF is a JCP standard, JSR 127 [JSR127], that defines a set of JSP tags and Java classes to simplify Web UI development. It is hoped that JSF will standardize tools and components by providing a single-component framework for JSP and servlets. JSF provides a framework for the presentation layer and also draws on the MVC concepts. JSF is a part of the Java EE 5 specification. Spring Spring offers a framework that covers the complete stack of the layers in a Java Web application. The framework implements the Inversion of Control and Dependency Injection design patterns uniformly across all components. It provides Spring MVC and Web flows for the presentation layer. It provides a light-weight container to implement the business logic using POJOs, and there- fore claims to eliminate the need for EJBs. It also provides solutions to manage the application data. Web Applications 129 OSGi is gaining momentum as a general service platform because it can scale from embedded devices to enterprise systems. Eclipse, and therefore WTP, is an example of an OSGi-based system. IBM and BEA are building their next-generation application servers using OSGi platforms. What is more interesting is that we can also use OSGi to develop simple business components and services that are assembled in runtime to provide business services. For example, you can run Spring 2.0-based applications on OSGi runtimes. Pico Container Pico Container is a light-weight framework that is also based on the Inversion of Control and Dependency Injection patterns. Similar to Spring, it also grew as a reaction to the complexity of J2EE development, specifically against the difficulties associated with EJB development. Hibernate Hibernate is an Object Relational Mapping (ORM) framework. It allows developers to implement object relational persistence and query services for POJOs without any modifications to Java code. The EJB3 Entity Beans specification, and specifically the Java Persistence API (JPA) that has evolved from it, increases the attractiveness of Hibernate and ORM frameworks alike to solve this difficult problem. Service-Oriented Architecture (SOA) SOA is about separating parts of your business into meaningful units, called serv- ices, and building applications that are integrated using services. Service orientation is encapsulation of business logic. A service is an application of a fundamental OO concept, separating the implementation from the interface. Combined with stan- dard languages such as XML, common protocols for transport such as HTTP, and the capability of searching and binding to a service provider at runtime, SOA has rapidly become the preferred integration technology for a diverse set of systems. SOA and Web services are based on many standards such as XML; XML Schema; Web Service Description Language (WSDL); Universal Description, Discovery, and Integration (UDDI); SOAP; JAX-RPC; and many WS-* specifications. A detailed description of SOA is beyond the scope of this book. However, we will describe how you can use WTP to build service-oriented Web applications, primarily using Web service technologies. Providing Services: The Service Layer The purpose of the service layer in your application is to expose your business and application capabilities as services. Your applications are only as interesting as the clients that use them. The classic question, if a tree falls in the forest and no one is there to hear it, does it make a sound? applies here. Many types of clients can use services: ❍ Rich Client Applications that consume services from many providers ❍ Embedded Systems, such as mobile phones 130 CHAPTER 5 • Web Application Architecture and Design ❍ Portals and Web applications, ranging from remote portals and Web appli- cations to the controller layer of a vertical system that uses a service layer to access the business model in an extended MVC with a service layer as described next ❍ Integration solutions using Business Process Execution Language (BPEL) to automate business processes ❍ Systems providing services by orchestrating others around a new business model Adding a Web service layer to your previous architecture (see Figure 5.6) allows you to create an application that is interoperable with many other systems. The additional layer will have entities such as Web services, service registries (UDDI), service contracts (WSDL), and proxies that bind these services to our applications. The service layer exposes well-defined interfaces to the same underlying business model. The service interface is defined by a service contract described using WSDL. Your business may have processes and logic that use services from external systems. The service consumers are not exposed to the details of the business model. All the technical details needed to consume a service are described in WSDL. Service-Oriented Architecture (SOA) 131 Service Model Persistence Layer Data Access Objects DB <<web service>> Service Interface Service Layer Business Model External Services Controller View Extended Model Other Clients Figure 5.6 Adding a Service Layer 132 CHAPTER 5 • Web Application Architecture and Design Consuming Services: Orchestration Applications consume services to aggregate content or services from service providers. You can provide new business processes by integrating services from a variety of providers and adding new business logic, rules, and capabilities. Existing content is recomposed and mapped into the business model of the client application, and it is presented in a new and unique way that is not necessarily available from any of the individual providers. This is the basic premise of SOA. Business process modeling and service orchestration can consume business services in a standard way by using Web services. The service layer provides an abstraction over a wide range of different business systems, and you can leverage these services to assemble business processes. WTP does not have tools for serv- ice orchestration, but vendors such as IBM, BEA, and Oracle have extended WTP to support the design and execution of these business processes. Business Process Execution Language (BPEL) is an OASIS standard to provide what is essentially an XML programming language for service orchestration. Where does SOA fit? It is useful to discuss how SOA fits with the traditional layers in our application. Some immediate questions to answer are: Is SOA a part of the presentation layer? Does SOA replace the presentation layer with a service layer? What about the business logic, where does it belong? A service does not have a view; therefore, there is no need to have a presentation layer. This is typically replaced with a service layer. A useful analogy is to think about the service layer as a form of the presentation layer; a service is a presentation of the business logic in a form that can be used by applications. The harder question is whether services are a part of the model and the business logic tier. The simple answer is no, but there is more to it. Business logic is not always modeled in a form that immediately can be made available as services: a good object model is fine-grained—lots of small, easy-to-understand objects with easy-to- understand methods. These objects encapsulate significant business concepts and data, but they are not very useful for creating services. Services are typically designed based on business use cases; they capture behavior for a flow of the events, such as “Pay for a reservation.” Fine-grained objects do not capture such flows. Services are a mix of business and application logic that capture processes and workflows. For example, in the League Planet application, the service layer would have an object that handles the creation of a new league. We’ll discuss the business logic tier in Chapter 8. Case Study: League Planet In this section, we develop the architecture of our fictitious League Planet Web site (see the Introducing League Planet section in Chapter 1). From an architectural viewpoint, League Planet is a multifaceted system with many different user profiles. First, there are the people who provide the content of the system. These are the people who are interested in sports and use League Planet to set up amateur sports leagues. They visit the Web site and create new leagues where they can record their teams, players, schedules, venues, scores, statistics, and many other kinds of information. League Planet needs to provide a highly dynamic Web front-end that will allow these users to interact with our system directly. As people use the system they navigate the pages in the Web site and perform actions such as viewing the information presented, filling in forms, and ordering goods offered by League Planet business partners. To support these users, League Planet will have a presentation layer. The presentation layer will be implemented using JSPs. To reduce the amount of Java code required to describe the UI, stan- dard Java tag libraries will be used. The presentation layer will be limited to code that displays information and accepts user input. Application flow and control will be delegated to a control layer. The control layer is responsible for tasks such as input validation, page flow and navigation, and collaborating with the business model layer to perform busi- ness tasks and to provide content to the view layer. The next profile for League Planet is the applications, such as the corporate sponsors, that will need services. League Planet generates an important part of its revenue from sponsored advertisements. The information about the teams, play- ers, visitors, and their user profiles can be used for targeted marketing. These pro- files are used to generate advertising banners and links to business partner sites. League Planet uses services to share this information. League Planet provides a service layer for its services and can access services from sponsors to show ads. Finally, League Planet supports partner organizations by providing most of its content and services online. Free and subscription-based information about the leagues, players, teams, visitor profiles, announcements, flash news, and lat- est real-time game results are only some of the services available. As a provider of services, League Planet is the source of unique content and services available for consumption by other applications. To implement this system, you use the architecture described in the previous section (see Figure 5.6 earlier). To demonstrate how this would work, consider the scenario described in the sequence diagram shown in Figure 5.7. Case Study: League Planet 133 [...]... news.jar Web content meta-inf MyBean.class EJB client.jar Figure 6 .3 J2EE Modules Creating Web Applications To build a Web application you need a project that contains a Web module There are two types of Web projects: static and dynamic Static Web projects contain resources that provide static content You can use a static Web project to develop Web applications that contain many of the standard Web resources,... CHAPTER 6 • Organizing Your Development Project Figure 6.8 Dynamic Web Project—LeaguePlanetWebProject Project Web Module WebContent JavaSource * WEB- INF * Resource Class * classes lib web. xml Resource Figure 6.9 Elements of a Dynamic Web Project * Resource 147 Web Project Types and J2EE Applications This is the Web application root All Web artifacts placed in this folder will be available to the client... of the Web application A dynamic Web project can publish its contents as a Java Web application archive (WAR) file (see Figure 6.10) Publishers assemble the artifacts in a Web project, such as Java sources; Web content, such as JSPs, HTML, and images; and metadata, such as Web deployment descriptors, in a form that can run on a J2EE application server LeaguePlanetWebProject LeaguePlanetWeb JavaSource/... a particular purpose A JDT Java project contains Java elements such as packages, types, methods, fields, and property files for creating Java programs A Java project knows how to build and run Java programs Each Java project has a Java builder that can incrementally compile Java source files as they are edited You can change the properties of a Java project, such as the Java build path The build path... provides Web projects that are sophisticated Eclipse projects that know about J2EE artifacts In addition to having basic Java project capabilities, a Web project can be used to organize J2EE artifacts into buildable, reusable units (see Figure 6.2) Simple Project Java Project Webtools Flexible Project Organizes resources Manages source code Understands java artifacts ( .java, class, .) Has Java builders... the J2EE Web deployment descriptor, web. xml (see Figure 6.8) 145 Web Project Types and J2EE Applications Figure 6.7 Web Module You have now created a dynamic Web project named LeaguePlanetWebProject and targeted it to Tomcat The Dynamic Web Project wizard creates folders and files under the project (see Figure 6.9) Open the project you have just created and browse its contents For example, the WebContent... (see Figure 6.9) The contents of WebContent will be accessible from the Web application context root The following default elements are created with a dynamic Web project: ❍ WebContent /WEB- INF /web. xml: ❍ src: This is the Web deployment descriptor This is the Java source code for classes, beans, and servlets The publisher will copy the compiled class files into the WEB- INF/classes folder of the final... example, the WebContent folder contains a special folder named WEB- INF, which holds items that are defined by the J2EE specification and are not accessible by a Web browser The WEB- INF/classes folder is where compiled Java code goes It also contains a special file, web. xml, which is the J2EE Web deployment descriptor The WebContent folder contains Web resources such as JSP and HTML files, and other types... for Web application directory structure It specifies the location of static Web files, JSPs, Java class files, Java libraries, deployment descriptors, and supporting metadata The default dynamic Web project layout resembles the structure of a J2EE Web application 142 CHAPTER 6 • Organizing Your Development Project module In the workbench, you can use the New Web Project wizard to create a new Web project... Project Explorer view, right click, and invoke the New ᭤ Dynamic Web Project menu item (see Figure 6.4) Figure 6.4 Select Wizard Click Next The New Dynamic Web Project wizard opens (see Figure 6.5) Web Project Types and J2EE Applications 1 43 Figure 6.5 New Dynamic Web Project 2 Enter LeaguePlanetWebProject for the project name A dynamic Web project contains J2EE components such as JSPs and servlets . 6.2 Web Projects Simple Project Java Project Webtools Flexible Project Organizes resources Manages source code Understands java artifacts ( .java, .class,. . .) Has Java builders Runs on a Java. project that contains a Web project and an EJB project with components for leagues and players. Figure 6.1 J2EE Applications and Web Projects Web Project Types and J2EE Applications 139 Web Projects Projects. JDT Java project contains Java elements such as packages, types, meth- ods, fields, and property files for creating Java programs. A Java project knows how to build and run Java programs. Each Java