(MVC) design mode

zhaozj2021-02-16  77

Id: users_guide.html, v 1.10 2000/08/10 23:45:27 craigmcc Exp $ Author: Jakarta Team http://jakarta.apache.org/ Translator: Li Kun (dlee) unruly_wind@163.net 1. Description 1.1 Model-View-Controller (MVC) Design Mode FixME - requires a general introduction to this pattern. (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 In the components and concepts, as shown below:

-------------------------------------------------- ------------------------------

?

-------------------------------------------------- ------------------------------

Each of the main components in 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

. In addition, there is a standard mechanism for defining your own tag, these customized tag organizations in the Custom Tag Library.

The Struts includes a broad easy to create a user interface, and fully international custom tag libraries that work with an actionform beans as part of the system model part of the system MODEL. The use of these tags will be discussed in detail later. In addition to the JSP page and its behavior and custom tags, business objects often need to be able to process themselves into HTML (or XML) based on their current state when they are requested. The output that has been processed from these objects can be easily used.

Standard behavior markers include in the JSP page in the results.

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 The JSP page uses a standard behavior tag, just like this: class = "com.mycompany.myapp.mycart" />

2.3 ActionForm Beans

The Struts framework typically assumes an actionform bean that you have created for each of your applications (a class that implements an Actionform interface). If you define such beans in your an actionMapping profile (see "Creating Controller Components"), Struts's Controller Servlet will automatically perform the following services before calling the appropriate action method:

Check if the user's session beans have an instance of the Bean in the SESSION of the user with the appropriate keyword.

If there is no such session range, a new bean is automatically created and added to the user's session.

The corresponding set method is called for each name corresponding to a attribute in the bean. This operation is similar to when you select all attributes using standard JSP behavior tags.

.

Updated ActionForm Bean will be passed to the actOn class's Perform () method to make these values ​​to take effect immediately.

When you write your Actionform Beans, remember the following principles:

The ActionForm interface itself does not require special implementation methods. It is used to identify the role of these specific Beans throughout the architecture. Typically, an actionform bean includes only attribute GET methods and SET methods, no business logic. Typically there is only a little input verification logic in an ActionForm Bean. The main reason for such beans is to save most of the recent value entered by the user-related forms - even when the error is detected - the same page can be rebuilt, accompanied by an error message, so that the user only needs Correct the wrong field. The authentication of the user input should be executed in the Action class (if it is very simple), or executes in the appropriate business logic beans.

Define an attribute (with the associated getxxxx () and setxxxx () method) for each form. The field name and attribute name must match the JavaBeans agreement. For example, an input field called UserName will cause the setUserName () method being called.

You should pay attention to the meaning of "form" as discussed here and should not have to correspond to a separate JSP page in the user interface. It is also common to extend to a "form" in many applications to multiple pages in many applications. Think about it, for example, the user interface of the navigation installer usually used when installing a new application. Struts encourages you to define a separate Actionform Bean that contains all field properties. Regardless of the fields actually display on which page is displayed. Similarly, different pages of the same form should be submitted to the same Action class. If you follow this suggestion, in most cases, the page designer can reorganize fields in different pages without changing the processing logic.

2.4 System status beans

The actual state of the system is usually represented as a set of one or more JavaBeans classes, which defines the current state. 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, in the following description) Translate all from http 2.6 Question out: Accessing relational database Many web applications use a relational database (via a JDBC Driver Access) to save your 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 one.

Will point to it.

In the init () method that starts the servlet () method, the instance of a ConnectionPool class is configured and saved as a servlet context property (from the JSP's point of view, the bean is equivalent to an Application range). 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 logic bean that requires database coupons (such as "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. Create 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 Message

A few years ago, application developers can consider only one language that only uses only one language (or sometimes two) and usually only one quantity of expressions (such as dates, digital, currency values). 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 - Basic support Internationalized Java class 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 = hellomyResources_xx.properties - Contains ISO language programming to "XX" (see the Java Document page for ResourceBund gets a current list) news. 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 Most of the web developers have used HTML standard performance to establish a form, such as using tags. 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)

Value = "<% = loginbean.getusername ()%>> This is hard to knock, it will make HTML developers without 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 situation uses Struts to handle the like this:

There is no need to explicitly involve JavaBean from which the initial value is obtained. This will be automatically processed by the frame.

3.3.1 Establishing a Find a complete registration form using the Struts How to demonstrate how Struts greatly reduces the pain of processing forms relative to the JSP functionality 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"% >

TYPE = "org.apache.struts.example.logonform" />

The following entries are based on this example of the key feature of processing 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. FORM tag based on the specified property to an HTML

转载请注明原文地址:https://www.9cbs.com/read-12974.html

New Post(0)