Struts User Guide

zhaozj2021-02-16  53

1. Introduction 1.1 Model-View-Controller (MVC) Design Mode FixME - requires a general introduction to this mode. (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, for example. 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 processed from these objects can easily use standard behavior tags in the JSP page in the result.

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: class = "com.mycompany.myapp.mycart" /> 2.3 Actionform Beanstruts framework usually assumes a creation of the input requested in each of your applications Actionform Bean (ie a class that implements an ActionForm interface). If you define such beans in your anctionsMaping profile (see "Creating Controller Components"), Struts's Controller Servlet will automatically perform the following services before calling the appropriate action method: Check the user with the appropriate keyword Is there an example of a Bean of the appropriate class in the session. 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: 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 System The actual state is usually represented as a group 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) 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:

Create 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 that 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 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 - 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 = ""> This is hard to knock your 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. Consider the page called Logon.JSP (from 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. The FORM tag is processed on an HTML element based on the specified property. It also associates all the fields in this form with a session range that holds the session range under the keyword LogonForm. This bean is used to provide an initial value for all input fields with names that match the attribute names in the bean. If the appropriate bean is not found, a new bean will be automatically created, using the specified Java class name. The Text tag is processed for an HTML element of "Text". In this case, the number of character locations occupying the browser screen is also specified. When the page is executed, it is the current value of the corresponding bean's UserName property (that is, the return value of the getUserName ()). A Password tag is similar. The difference is that the browser will respond to the asterisk character when the user is knocked into their password instead of the input value. Submit and RESET marks the corresponding buttons in the form low. The text tag of each button is built using the Message tag, and there is a prompt, so these values ​​are international. 3.3.2 Enter Field Type Support Struts Define the tag for all the following types of input fields, with an overlinked that corresponds to its corresponding reference information. CheckBoxes Hidden Field Password Enter Field Radio button RESET button SELECT list and embedded Options Submit button Text Enter field Textareas In all cases, a field tag must be nested in an Form tag, which knows which bean is initialized Value. 3.3.3 Other useful means that there are several other tags in the tag library of Struts. There are several other tags for the establishment of the user interface: Enumerate repeats a marker for each element of a specified set (can be an enumeration, a HashTable , An array of VECTOR or an object). GetProperty Gets the specified property from the specified bean, and the rest of this page exists as a bean in a PAGE range. This is a convenient way to access a collection of enumerate. IfAttributeExists evaluates the marker only when a specified property is present in a specified range. IfttributeMissing is only available when a specified property does not exist in a specified range.

Ifparameterequals evaluates the marker only when a specified request parameter has a specified value. IfParameterNotequals delivers the marker only if the specified request parameter does not have a specified value or does not exist. IfParameterNotnull is only available to the marker in this request in this request in one specified request parameter and the length is greater than 0. IfParameternull delivers the marker only if the specified request parameter is not included in this request or the length is equal to 0. Iteerate repeats a marker for each element in a specified collection (can be a Collection, an Iterator, a MAP, or an object array). This tag replaces the Enumerate tag in the Java2 environment. Link generates a super connections that automatically applies the URL programming when there is no cookie support to maintain the SESSION state. Parameter Processing the value of the specified request parameter, properly filtering the character in HTML. Property displays the bean property named in a form - use this tag when the property should be read-only instead of the Text tag. 3.3.4 Automatic Form Verification In addition to the form of forms and beans described above, if your bean knows how to verify the input field it receives, Struts also provides an additional mechanism. To take advantage of this feature, your bean class implements the ValidatingActionform interface instead of an Actionform interface. A ValidatingActionForm adds an additional method signature: public string [] validate () for a method called by the Controller Servlet in the bean property already assembled but at the corresponding behavior class, the validate () method has The following options: Perform the appropriate verification found No error - Returns NULL or a non-0 length string array, and the controller servlet will continue to call the appropriate Action class Perform () method. Perform appropriate verification found There is an error - return a string array of the error message key (enter the application's MessageResources package) that should be displayed. The Controller Servlet saves this array as the request attribute suitable for marking and redirects the control back to the input form (identified by this actionMApping INPUTFORM property). As mentioned earlier, this feature is completely optional. If your Form bean only implements an ActionForm interface, the Controller Servlet will assume that any request is complete by the Action class. 3.4 Other expressions Despite the appearance of your application's appearance and feels based on standard JSP capabilities and Struts's custom tag library, you should also consider developing other improvement components reuse, reducing management burden, or reduces errors. Several optional techniques are discussed below. 3.4.1 Application-specific custom tags are easy to build a tag for the application you created by using the custom tag provided by the Struts library to help create a user interface. Struts included examples with the establishment of the following only to implement this application's tag demonstrated this principle: Checklogon - Check the existence of a special session object, if there is no redirection to the registration page. This is used to capture such a situation, and the user makes a page on your application to make a bookmark and try to skip the registration, or the user's session timeout. LinkSubscription - Generates an overlink for a detailed order page, which will be passed as a request attribute as a request attribute. This is used when listing the order associated with a user and provides an editing or deleting a set of order.

Linkuser - Generates an overlink for a specific page of a user, which will pass it as a primary keyword value as a request attribute. These tagged source code in the SRC / EXAMPE directory, in the package org.apache.struts.example, there are some other Java classes in this application. 3.4.2 Creating a full representation in a JSP file (including custom tag and dynamic data including custom tags and beans to access requests) is a very ordinary design method, in the example program included in Struts. . However, many applications require a plurality of logical independent parts of your application in a single page. For example, an inlet application can have some or all of the following functions on the main page of the entrance:

Visit a search engine for this entry. One or more "providing news" is displayed, including the title of interested in accordance with the user's registration information. Access the topic of discussions related to this entrance. If your entrance provides free mail account, there must be a "mail waiting" tip. If you can divide your work, allocate different developers to do different fragments, then the development of different fragments of this site will be simpler. Then, you can use the INCLUDE capabilities of JSP technology to combine these clips into a separate page. There are two include use, depending on what time you want the output, the incrude command () is compiled during the JSP page. It is used to include HTML code that does not require changes in request. It puts the text included as static text, very like C or C #include instructions. Include behavior () is processed during request and is transparently processed by the server. This means you can perform include Include by nested it in a mark similar to ifparameterequals. 3.4.3 Image Processing Components Some applications require dynamically generating pictures, just like a price chart at a stock market report site. Two different methods are usually used to implement this requirement: handling a URL that performs a servlet request. This servlet will use an image library to generate a picture, set the appropriate Content type (for example, image / gif), and send the image stream to the browser. The browser will display pictures like it is received from a static file. Processing an HTML code requires downloading a Java Applet for an image that creates a request. You can receive this image by setting the appropriate initialization parameter for this applet in the process of processing, or you can make this applet to establish your own join to receive these parameters. 4. Creating a Controller component 4.1 Overview Now we understand how to construct your application's Model and View components, now is the time to concentrate to the Controller component. The Struts includes a servlet that implements the main functionality of a request URI to a behavior class. So your main responsibility related to Controller is: Write an Action class for each possible logic (that is, an Action interface implementation) writes a defined class name and other information related to each possible mapping. Class (i.e., implementation) Write behavior mapping profile (using XML) to configure the Controller Servlet. Updating your application Update Web Application Deployment File (XML) is used to include the required Struts component. Add appropriate Struts components to your app. 4.2 Action Action class method of a single interface definition must be implemented by an Action class, as follows: public ActionForward perform (ActionServlet servlet, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; a Class Action The goal is to process this request, then return an ActionForWard object that identifies the JSP page, and the control should redirect this JSP page to generate a corresponding response.

In Model 2 design mode, a typical Action class will implement the following logic in its Perform () method: Verify the current state of the user session (for example, check the user has successfully registered). If the Action class discovery is not registered, the request should be redirected to the JSP page that displays the username and password for registration. It should be done because the user may try to enter your application from "middle" (that is, from a bookmark), or because the session has timed, a servlet container creates a new session. If the verification has not occurred (because the FORM BEAN that implements the ValidActionActionform interface, verify the properties of this form bean are required. If a problem is found, as a request attribute saves the right error message keyword, then the control redirection back the input form such that the error can be corrected. Execute the required processing to process this request (for example, saving a row in the database). This can be done with code embedded in the Action class itself, but a suitable method of a business logic bean should usually be called to execute. The update will be used to create a server-side objects for the next user interface page (typically the Request range or session range beans, definition you need to keep these items available). Returns an appropriate ActionForward object that identifies the JSP page that generates a response, based on a newly updated Beans. Typically, you will pass the ActionMapping object in your reception (if you use a local logical name on this map) or in the Controller Servlet itself (if you use a global logical name) to call Findforward () Get a reference to such an object. The design points to remember when programming for the Action class include the following: Controller Servlet only creates an instance of your Action class for all requests. This way you need to write your Action class to run correctly in a multi-threaded environment, just like a service () method you must safely write a servlet. The most important principle for helping thread security program is to use only local variables in your Action class rather than instance variables. Local variables are created in a stack assigned (by your JVM), so there is no need to worry about sharing them. Although it should not, Beans that represent the Model section in your system may still throw a violation. You should capture all such violations in the logic of your Perform () method, and record them in the application's log file (including the appropriate stack tracking information): servlet.log ("Error Message Text) by performing the following statement (including the corresponding stack tracking information): servlet.log ", Exception); As a general rule, allocate little resources and keeping them in the request from the same user (in the user's session), it will lead to scalability issues. You should work hard to release such resources (e.g., database coupling) before you want to redirect to the appropriate View component - even when a BEAN you calls thrown a violation. In addition, you will want to prevent a very large Action class. The simplest implementation is to embed your functional logic into the Action class itself, rather than writing it in a separate commercial logic beans. In addition to making the Action class is difficult to understand and maintain, this method also makes it difficult to reuse these business logic code because the code is embedded in a component (Action class) and is bundled in a web application environment.

Included in the example program in Struts extends this design principle because the business logic itself is embedded in the Action class. This should be considered as a bug in this sample application design, rather than a Struts architecture, or a way to be equivalent. 4.3 ActionMapping Implementation To successfully run, Struts's Controller Servlet needs to know how to map how to map to an appropriate Action class for each URI. Knowledge packages that need to be understood are in a Java interface called ActionMapping, which has the following properties: ActionClass - A complete Java class name for this mapped ACTION class. The first one-specific mapping is used, and an instance of this class will be created and saved for later reuse. Formattribute - The name of the bean range of the Session range, the current map of ActionForm is saved under this bean. If this property is not defined, there is no ActionForm being used. FormClass - A complete Java class name used for this mapped Actionform class. If you are using support for Form Beans, an instance of this class will be created and saved (in the current user session) PATH - Match the URI path to select this mapping request. Look at how to match the example below. Struts included an ActionMApping interface in a class called ActionMappingBase. If you don't need to define any additional properties for your own mapping, although this class is described as your ActionMApping class, you can configure it to the bottom. However, defining an actionMApping implementation (mostly the extended actionMAppingBase class) is also possible to include additional properties. The Controller Servlet knows how to automatically configure these custom properties because it reads the configuration file using the Struts Digester module. Included in the example program of Struts, this feature is used to define two additional properties:

Failure - If the Action class detects some of the issues of the input field it receive, the control should be redirected to the context-related URI. Typically, it is a request swivel JSP page name, which will cause a form to be reset (including an error message for the Action class setting, and most of the most recent input values ​​from Actionform Beans). SUCCESS - If the Action class successfully executes the request, the control should be redirected to the context-related URI. Typically, the JSP page name of the next page of the session stream of this application is prepared. With these two additional properties, the Action class in the example program is almost completely independent of the actual JSP page name used by the page designer. This page can be renamed when redesigned, but hardly affect the Action class itself. If the name of the "next" JSP page is hardcoded into the Action class, all these classes need to be modified. 4.4 How do you know what you want to get? Write a simple initialization of new an actionMApping instance and calling all the small Java classes for all appropriate SET methods (but very troublesome). In order to make this processing simple, Struts includes a Digester module to handle an XML-based description of an idealed map while creating an appropriate object. Look at the API documentation to get more information about Digester. The developer's responsibility is to create an XML file called Action.xml and put it in your application's web-inf directory. (Note that this file does not require DTD, because the actual properties actually used to different users can be different) must be, in this element is an embedded 0 or more elements - each one Corresponds to a mapping you want to define. The action.xml file from the example program includes the following map of the "Register" feature, we use to explain this demand:

ActionClass = "org.apache.struts.example.logonaction" formattribute = "logonform" formclass = "org.apache.struts.example.logonform" Inputform = "/ logon.jsp">

Just like you can see, this mapping matching path / logon (actually, because the example is used to match, you are over /logon.do's URI specified by a JSP page). When a request to match this path is received, an instance of a LogonAction class will be created (only first) and is used. The Controller Servlet will find a session range under the keyword logonform, if you need to create and save a bean for the specified class. This Action element also defines a logical name "Success" that is used in the LogonAction class to identify the page that is used when a user is successfully registered. This is like this to use a logical name to allow the Action class to isolate the page name change that may occur due to redesign positions.

This is the Forward element that the second declared outside any action so that it can be obtained in all the Action. In this case, it defines a logical name for the registration page. When you call mapping.forward () In your Action code, Struts first looks for the logical name of this Action local definition. If you are not found, Struts will automatically find the logical name for global definitions.

4.5 Web Application Expand Descriptor Settings The final steps of the application are configured to expand descriptors (saved in file web-inf / web.xml) to include all necessary Struts components. As an expanded descriptor of an example of a guide, we see the following entry needs to be created or modified. 4.5.1 Configuring an Action Servlet instance Add an entry definition Action servlet itself while including the appropriate initialization parameters. Such an entry looks like this: action org.apache.struts.action.ActionServlet aram> application org.apache.struts.example.ApplicationResources config /WEB-INF/action.xml debug 2 mapping org.apache.struts.example .Applicationmapping 2

The initialization parameter supported by the Controller Servlet is described below, copies Javadocs from the ActionServlet class. Square bracket description If you don't provide a value assumed by the initialization parameter, the default value assumed. Application - Application resource package base class's Java class name. [NONE]. Config - Context related to the XML resource of the configuration information. [/Web-inf/Action.xml] Debug - This servlet debug level, which controls how much information is recorded in the log. [0] Digester - We use the Digester debug level in initmapping (), which records the system.out instead of the servlet log. [0] Forward - Java class name implemented using the ActionForward. [org.apache.struts.Action.ActionForward] mapping - the Java class name implemented by using the actionMapping. [Org.apache.struts.Action.ActionMappingBase] Nocache - If set to TRUE, add HTTP header information to all responses to make the browser to generate or redirect any response to the buffer. [false] NULL - If set to True, set the application resource to return null if the unknown message key is used. Otherwise, an error message including unwelcome message key will be returned. [TRUE] 4.5.2 Configuring Action Servlet mapping There are two usual methods to define the URL-prefix matching and extension matching that will be processed by the Controller Servlet. One suitable mapping entry for each method will be described below. Prefix match means you want to pass all URLs at the beginning of a special value (after the context section). Such an entry looks like this:

Action / Execute / *

It means that a URL that matches the previously described / logon path looks like this: http://www.mycompany.com/myApplication/execute/logon here / myapplicationis is your application expands the context path. On the other hand, the extended mapping matches the URL to the Action Servlet based on the fact that the URL ends with a set of sentences that follow the definition of a set of characters. For example, JSP processing servlet is mapped to * .jsp mode, which is called when requested by each JSP page. In order to use * .do expansion (it means "do something") mapping entry should look like this:

Action * .do

And a URI that matches the previously described / logon path can look like this: http://www.mycompany.com/myApplication/logon.do4.5.3 Configuring the Struts Tag Library Next, you must add a definition struts The entry of the tag library. This entry should look like this: /Web-inf/struts.tld/web-inf/struts.tld

It tells the JSP system where to find this library's tag profile descriptor (on your application's web-inferon, not some place on the Internet). 4.5.4 Adding Struts Components To your application To use Struts while your application is run, you must copy the struts.tld file to your web-inf directory, copy the struts.jar file to your web- INF / LIB. ?

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

New Post(0)