Struts framework builds Controller components

zhaozj2021-02-16  70

1. Overview In the Struts architecture, Controller is primarily an ActionServlet, but the operation of business logic is mainly made by Action, ActionMApping, ActionForward. Among them, Action plays an implementation of true business logic, and ActionMapping and ActionForward specify the direction of operation of different business logic or processes.

The Controller section of the application is concentrated from the client receiving request (typically a user running a browser), which determines what business logic function is executed, and then generates the responsibility of the next user interface to give an appropriate View component. 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 us to save additional information specific to our applications, while still using the remaining characteristics of the framework. In addition, Struts allows us to define controls to redirect the logical name, such a behavior method can request the "Main Menu" page without having to know what the actual name of the corresponding JSP page is. This feature greatly helps us separate control logic (what is going on next) and display logic (what is the name of the corresponding page).

Second, Creating the Controller Component Struts includes a servlet that implements the main functionality of a request URI to a behavior class. Therefore, our main responsibility related to Controller is to write an Action class for each possible reception, that is, an Action interface implementation); write a defined class name and other information related to each possible mapping The ActionMapping class (that is, an ActionMapping interface implementation); Write behavior mapping profile (using XML) is used to configure the Controller Servlet. Updating the web application to the application to expand the descriptor file (using XML) to include the required Struts component, we add the appropriate Struts component to your application. 1. Action Implementation Action Interface Defines a single way to implement by an Action class, like this:

Public ActionForward Perform (ActionServlet Servlet, ActionMApping Mapping, Actionform Form, HttpservletRequest Request, HttpservletResponse Response) throws oException, servletexception;

The goal of an Action class 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. The STRUTS architecture only creates an instance for each Action class in the application system. Because all users use this instance, you must determine your Action class in a multi-threaded environment.

Note that the Action subclass of the customer inherits himself must override the execute () method because the Action class returns NULL by default. 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 our app 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, define how we 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, we will use the received ActionMapping object (if we use a local logical name on this map) or in the Controller Servlet itself (if we 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 our Action class for all requests. This way we need to write our Action classes to operate correctly in a multi-threaded environment, just like we must safely write a service () method of a servlet. The most important principle for helping thread security program is to use only local variables in our Action class rather than instance variables. The local variable is created in a stack assigned to each request thread, so there is no need to worry about sharing them. Although it should not, Beans in the Model section in our system may still throw violations. We should capture all such violations in the logic of our Perform () method, and record them in the application's log file (including the corresponding stack tracking information): servlet.log ("Error Message Text) by performing the following statement "", Exception;

As a generic rule, there are few resources that are rare and maintain them in requests from the same user (in the user's session), which will cause scalability. In addition, we will want to prevent a very large Action class. The simplest implementation is to embed our functional logic into the Action class itself, rather than writing it in an independent business 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.

2, ActionMapping Implementation In order to successfully run, Struts's Controller Servlet needs to know how to map to a proper 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: The full 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: The complete Java class name used for this mapped Actionform class. If we 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 we don't need to define any additional properties for our own mapping, although this class is made as our ActionMapping class, it is configured 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. In an example program included in Struts, this feature is used to define two additional properties: failure: If some of the Action class detects some of the issues it receives, 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 functionality, 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. 3. The ActionForWard implementation is to forward the processing results of the Action class to the destination. The Action class gets the handle of the ActionForward instance, and then use three methods to return to the ActionServlet, so we can use the actionforward (): ActionServlet, get a global forwarding according to the name; an ActionMAppin instance is transmitted to the Perform () method, and find a local Forward. The other is to call the following constructor to create an example: public actionforward () public actionforward (String path) Public ActionForward (String Path, Boolean Redirect)

4, Action mapping configuration file

How does the controller servlet know what we 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. The developer's responsibility is to create an XML file called action.xml and put it in our application's web-inf directory. (Note that this file does not require DTD, because the actual use of the attributes can be different from the outermost XML element must be in this element, 0 or more in this element. Element - Each corresponds to a mapping we 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:

Just like we have seen, this mapping matching path / logon (actually, because the example is used to match, we end in /logon.do in /logon.do in the request specified by the 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 we call mapping.forward () In our Action code, Struts first looks for the logical name defined by this Action. If not found, Struts will automatically find the logical name of the global definition.

5, web application deployment descriptor

The final step of setting an application is to configure an application deployment descriptor (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. 1) Configure an ActionServlet instance

Add an entry definition ActionServlet itself while including the appropriate initialization parameters. Such an entry looks like this:

action org.apache.struts.Action.ActionServlet Application Org.apache.struts.example.ApplicationResources config /Web-inf/Action.xml debug 2 < / init-param> 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 we do not provide a value assumed by the initialization parameter to assume a default value.

Application: Application resource package base class Java class name. [None]

Config: The context-related path containing the XML resource of the configuration information. [/Web-inf/Action.xml]

Debug: The debug level of this servlet, which controls how much information is recorded in the log. [0]

Digester: We use the Digester's debug level in Initmapping (), which records SYSTEM.out instead of

A servlet's log. [0]

Forward: The Java class name implemented using the ActionForward. [org.apache.struts.action.Actionforward]

Mapping: The Java class name implemented using an 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 keyword is used. Otherwise, an error message including unwelcome message key will be returned. [True]

2) Configure an ActionServlet mapping

There are two usual ways to define the URLs that will be processed by the Controller Servlet: prefix matching and extension matching. One suitable mapping entry for each method will be described below.

Prefix match means we want to pass all URLs at the beginning of a special value (after the context path part) to this servlet. 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.mystudy.com/myapplication/execute/logon

Here / myApplication is the context path where our application expands.

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 request previously described / logon path can look like this:

http://www.mystudy.com/myapplication/logon.do

3) Configure the Struts tag library

Next, we have to add an entry that defines the Struts tag library. This entry looks like this:

/web-inf/struts.tld /web-inf/struts.tld

It tells the JSP system where to find the tag library descriptor of this library (in our application's web-inf directory).

4) Add Struts component to our application

In order to use Struts while our application is running, we must copy the struts.tld file to our web-inflicity, copy the struts.jar file to our web-inf / lib.

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

New Post(0)