Author: Jakarta Team http://jakarta.apache.org Translator: Li Kun (dlee) unruly_wind@163.net 1. Introduction 1.1 Model-View-Controller (MVC) design pattern FIXME - this mode requires a general Introduce. (Translation: You can refer to the "design mode" of Machinery Press.) 1.2 Map MVC Concepts into the Struts Components The architecture of Struts implements the concept of Model-View-Controller design mode, which maps these concepts to web applications Components and concepts. Each of this architecture will be discussed in detail below. 1.3 Model: System Status and Business Logic JavaBeans MODEL section in the MVC-based system can be subdivided into two concept-system internal states, and can change the status of the state. In terms of syntax terms, we can use status information as named (things), regard behavior as verbs (changes in things). In general, your application represents the state inside the system as a set of one or more JavaBeans, using the property (Properties) to represent the details of the status. Depending on your application's complexity, these Beans can be self-contained (in some way to know how to keep their status information permanently), or can be positive (Facades), know how to be from outside when being requested Information in data sources (such as databases). Entity EJBS is often also used to represent internal states. Large applications often represent system possible business logic behavior as a method called Beans that can be maintained. For example, you have a shopping cart bean saved in the session for each current user, which means that the current user decides the properties of the item. This bean has a checkout () method to verify the user's credit card, which will be ordered to the warehouse to select the goods and shipments. Other systems represent the same behavior, perhaps use Session EJBS. In some small applications, the same behavior may be embedded in the Action class as part of the Controller. This is appropriate when logic is very simple or does not want to reuse these business logic in other environments. The STRUTS framework supports all these methods, but it is recommended to separate business logic ("what") and Action class ("what to do") separate. 1.4 View: JSP page and the VIEW portion representing the component Struts is usually built using JSP technology. The JSP page contains a static HTML (or XML) text called "Mode Text", plus the dynamic content of the inserted interpretation of special behavior markers. The JSP environment includes its use of a set of standard behaviors that are described by JSP specifications, such as
1.5 Controller: ActionServlet and ActionMApping application's Controller section focuses on receiving requests from the client (typically a user who runs a browser), decides what business logic functions, and then generate the responsibility delegation of the next user interface to one Appropriate view components. In Struts, the basic component of Controller is a servlet for an ActionServlet class. This servlet is configured by defining a set of mappings (described by Java Interface ActionMApping). Each map defines a path with the requested URI and an Action class (a class that implements an Action interface), which is responsible for performing the expected business logic, then assigns control to the appropriate View component. Create a response. The Struts also supports the ability to use an ActionMApping class that includes additional properties other than standard properties necessary to run the framework. This allows you to save additional information specific to your application, while still using the rest of the frame. In addition, Struts allows you to define controls to redirect logical names, such a behavior method can request the Main Menu page (for example) without knowing the actual name of the corresponding JSP page. This feature greatly helps you separate control logic (what to do next) and display logic (what is the name of the corresponding page). 2. Creating Model Components 2.1 Overview The demand document for the application you use is probably to create a user interface. However, you should guarantee that the processes needed for each submitted request must be clearly defined. In general, developers of Model components focus on creating JavaBeans classes that support all feature requirements. The precise characteristics of Beans, which requires special application requirements, dependent on specific demand changes, but they can usually be divided into several types discussed below. However, it is useful to be a short review for the "range" concept because it is related to Beans. 2.2 JavaBeans and Range In a web-based application, JavaBeans can be saved in (and access) some of the different "properties" collections. Each collection has a set of rules for the surplus and the Save Beans visibility. In general, these rules that define lifetime and visibility are called these beans. The following terms will be used in the JSP specification (equivalent to defining the servlet API in parentheses): Page - Beans visible in a separate JSP page, the survival period is limited to the current request. (Partial variables in the service () method) Request - Beans visible in a separate JSP page, including all page or servlets that are included in this page or redirected from this page. (Request Attribute) Session - Participated in all JSPs and servlets of a specific user session, across one or more requests. (Session attribute) Application - All JSP pages of a web application and Beans visible from servlet. (Servlet Context Attribute) Remember that the JSP page with the same web application and servlets share the same set of bean collections.
For example, a bean is saved as a request attribute in a servlet, just like this: mycart mycart = new mycart (...); Request.settribute ("cart", mycart); will immediately be redirected by this servlet JSP page uses a standard behavior tag, just like this:
For example, a shopping cart system includes a bean that represents a shopping cart, which is maintained for each individual shopper, including (in other things), a group of shoppers currently choose to purchase items. Divided, the system also includes saving user information (including their credit cards and delivery addresses), which can get the directory of the project and their current inventory levels. For small-scale systems, or for status information that does not require long-term saving, a set of system status beans can contain information for specific details that all systems have experienced. Alternatively, the system status beans represents information that is permanently saved in some external databases (for example, the CustomerBean object corresponds to a specific line in Table Customers), and creates or clears from the server's memory when needed. In large-scale applications, Entity EJBS is also used in this purpose. 2.5 Business Logic Beans You should encapsulate functional logic in your application into a method called for JavaBeans designed for this purpose. These methods may be part of the same class as the system status beans, or may be in a separate class specifically performing business logic. In the latter case, you usually need to pass system status beans to these methods as parameter processing. For the maximum reusability of code, business logic Beans should be designed and implemented to do not know that they are executed in a web application environment. If you find that you must Import a Javax.Servlet in your bean, you will bundle this business logic in a web application environment. Consider reorganizing things to make your Action class (part of the Controller task) Translate all information requested from the HTTP request to be called to your business logic Beans property set method, then you can issue an Execute () Call. Such a business logic class can be reused in an environment other than the Web application that is initially constructed. Depending on your application's complexity and scope, commercial logic Beans can be a normal JavaBeans interacting with system status beans that is passed as parameters, or use JDBC to invoke ordinary JavaBeans for accessing the database. For larger applications, these Beans are often state or stateless EJBs. 2.6 Summary: Accessing Database Many web applications use a relational database (accessible through a JDBC DRIVER) to save the application-related permanent data. Other applications use Entity EJBS to implement this purpose, they delegate EJBS to determine how to maintain permanent status. If you are using EJBS to implement this purpose, follow the client design patterns described in the EJB specification. For web applications accessible based on direct database, a normal design problem is how to generate an appropriate JDBC connection object when accessing the low-level database. There are several ways to solve this problem - the following principles describe a method of recommendation: Creating or get a ConnectionPool class that allows a set of database connections to be shared by multiple users. Struts does not include such a class, but there are many such classes to get. When the application is initialized, a servlet with a "Launch" value is defined in the application deployment descriptor. We will call this servlet to start servlet. In most cases, this servlet does not need to handle any request, so there is no
It is convenient to configure the connection buffer pool based on delivery to the start-up servlet initialization parameter. In the destroy () method of the servlet, the logic of the connection opened by the released buffer pool is included. This method will be called when the Servlet container ends this application. When the Action class needs to call a method in the business logical bean that requires database coupons (for example, "INSERT A New Customer"), the following steps are required: Get a join buffer pool object from the ServelT Context property for this web application. Call the open () method of the coupling pool object to get a join in the Action class call. Call the appropriate method in the business logic bean, passed the database access object as a parameter to it. Call the Close () method in the allocated join, which will cause this connection to reuse the reuse of other requests to be returned to the buffer pool. A usual programming error is to forget to return the database to the buffer pool, which will eventually lead to all the coupling. Be sure to be sure that the logic of the Action class always returns the join, even when a business logic bean throws a violation. Follow the above recommended design patterns that you can write your business logic, don't need to worry about how they get a JDBC join - simply contains a Connection parameter in any way to access the database. When your business logic class is used in a web application, allocation and release the appropriate join is the responsibility of the Action class. When you use the same business logic class, for example, in a batch work, provide an appropriate join is the responsibility of that application (this does not need to be obtained from the buffer pool, because most batch work runs on a single single Thread environment). 3. Creating a View Component 3.1 Overview This chapter focuses on the task of creating the VIEW component in the application, mainly using JSP technology. In addition, Struts provides support for the establishment of an international application in addition to the interaction with the input form. Several other related topics related to View are also simply discussed. 3.2 International News Averaged a few years ago, application developers can consider only use only one language (or sometimes two) and usually only a number of expressions (such as dates, numbers, currency values). Residents. However, the explosive growth of web technology-based applications, as well as to expand these applications over Internet or other widely accessed networks, have made the country's boundaries to immune. This change is converted into an internationalization of the application (often referred to as "I18n" because 18 is the number of letters between the letters "I" and the letters "N") and localization needs. Struts is built on the Java platform to build international and localized applications. The key concept that needs familiarity is: Locale - the basic Java class supported by the foundation is java.util.locale. Each Locale represents a special country and language selection (plus an optional language variable), and a set of formats assume, such as numbers and dates, and more. ResourceBundle - Java.util.resourceBundle class provides basic tools that support multiple language messages. To view more about internationalization about the ResourceBundle class and your JDK version of the documentation. PropertyResourceBundle - A standard implementation of a RESOURCEBUNDLE class allows you to define resources using the same "name = value" syntax with the initialization Properties file. This is very convenient for preparation resource packages that use for a web application because these messages are usually for text.
The MessageFormat - Java.Text.MessageFormat class allows you to replace a message in a message string using the parameters (in which case is a message obtained from a resource package). This is useful in the occasion you create a sentence, but the word will appear in a different order in different languages. The placeholder string {0} in the message is replaced with the first runtime parameter, and {1} is replaced with the second runtime parameter to push. MessageResources - Struts class org.apache.struts.util.MessageResources enables you to make a resource package to make a database and allow you to request a specific message for a specific Locale (usually corresponding to the current user), Instead of running the default Locale request message in which the server is run. For an international application, create an attribute file containing messages for each language in accordance with the steps described in the JDK document package. The following example will be given. Suppose your source code is built in the package com.mycompany.mypackage, so it is saved in a directory called (relative to your source directory) COM / MyCompany / mypackage. To create a resource package called com.mycompany.mypackage.myResources, you should create the following files in the directory COM / MyCompany / MyPackage: MyResources.properties - contains messages for your server's default language. If your default language is English, you may have a such entry: prompt.hello = hello myresources_xx.properties - Contains ISO language programming to "XX" (see the Java Document page for the ResourceBundle get a current list connection) Message. For the French version of the above message, you can have this entry: prompt.hello = Bonjour You can have any of the resource package files you need. When you configure the Controller Servlet in the web application deployment, you need one thing that you need to define in an initialization parameter is the base name of the application's resource package. In the above case, this should be com.mycompany.mypackage.myResources. 3.3 Forms and FormBeans Interaction Most of the Web Developers have used HTML standard performance to establish a form, such as using the tag. The user wants the interactive program to have a certain behavior. One of these expectations is related to the error handling - if the user has an error, the application should allow them to only modify the part you need to modify - without the need to retrieve the current page or form Any other information. Using standard HTML and JSP programming, this expectation is monotonous and heavy. For example, an input element of a username is like this (in JSP) > this It's hard to knock your pair, you will make HTML developers who have no programming concepts, and will cause problems in the HTML editor. Instead, Struts provides a comprehensive mechanism based on JSP 1.1 custom tag library function to establish a form. The above case uses the Struts to process the like this:
3.3.1 Establishing a complete registration form using the Struts How to demonstrate how Struts greatly alleviates the pain of processing forms relative to JSP functions directly using HTML and standard. Considering the following, the following is called Logon.jsp, page (from Struts): <% @ page language = "java"%> <% @ taglib URI = "/ web-inf / struts.tld" prefix = "struts"% >
| |
---|---|
| |
struts: reset> td> tr> table> struts: form> body> < / HTML> The following entry is based on this example of the key feature that handles a form in Struts: Taglib instruction tells the JSP page compiler to find the tag library descriptor of the Struts tag library. In this case, we use Struts as a prefix to identify tags from this library, but you can use any prefix you want to use. This page uses several Message tags to find an international message string from a MessageResources object containing all resources of this application.
| In order to make this page work, the following message key must be defined in these resources: logon.title - Title of the registration page Prompt.userName - a "username:" prompt string Prompt.password - a "Password:" Tip String Button.Submit - "Submit" button Tag Button.Reset - The Tag of the "reset" button When the user registers, the application can save a Locale object in the user's session. This Locale will be used to select a message in the appropriate language. This makes it easy for the user to switch the user's option - only change the saved locale object, and all messages are automatically switched. Errors tag Displays any error message saved by a business logic component, or if there is no error message, it doesn't have anything. This marker will be described in depth below. The Form marker is processed by an HTML |