The class provided by Struts

xiaoxiao2021-03-06  100

The Struts framework has the advantages of module, flexibility, and reuse of the components, and simplifies the development of MVC-based web applications. This chapter discusses the Struts architecture in detail. We will see how Struts clearly define control, transaction logic, and appearance, simplifying the development of application processes. We will also introduce how the class provided by Struts makes development work more simple, including: 1. Control program process class 2. Class 3 implement and execute program transaction logic class 3. Customized tag library makes created and verified HTML forms more Easy 1.1 Struts Compressed Pack Content Folder Jakarta-Struts-1.0.2 contains two directories, libs, and webapps. In the lib directory, you have the use of Struts to create an application is the required file: file description JDBC2_0-stdext.jar contains a JDBC2.0 Optional Package API class. If we want to use the data resources provided by Struts, you need to copy this file to web-inf / lib with all Java classes in the Struts. Also need to be copied to web-inf / lib * .tld tag library descriptor file, describe custom tags in multiple Struts tag libraries. Also copy to WebAPPS directory under WebApps directory under WebApps directory: Web application Description Struts-blank.war A simple web application struts-documentation.war contains all Struts Site on all Struts documents Struts-Example.war Struts Many Demonstration Struts-EXERCISETAGLIB.WAR is mainly used to add a test page that is used to use the custom label library, but it can also demonstrate how to use the struts tag struts-template.war contains the introduction and example of the Struts template tag Struts-UploadAd A simple example, demonstrating how to use the Struts framework to upload file 1.2 Struts architecture allows us to observe three parts in the component frame in the Struts frame from the MVC angle: model, window and controller. 1.2.1 Model In the Struts framework, the model is divided into two parts: the internal state of the system can change the status of the state (transaction logic) internal state is usually represented by a set of actinform javabean. These beans may be self-contained and have a continuous state depending on the design or application complexity, or data (from a database) is only available when needed. Large applications are typically encapsulated transaction logic (operation) in method, which can be called the bean call. For example, shopping cart bean, it has information about purchasing goods, there may be a checkout () method to check the user's credit card, and send information to the warehouse. In a small program, the operation may be embedded in the Action class, which is part of the controller role in the Struts framework. This method is very suitable when logic is simple. It is recommended that users separate transaction logic (what to do) with the role (decision to do) played by the Action class. 1.2.2 Window is created by JSP, and Struts contains extended custom label libraries to simplify the process of creation of fully international user interfaces. 1.2.3 In the Controller Struts, the basic controller component is the instance servert in the ActionServlet class, and the actually used servlet is defined by a set of mappings (described by the ActionMApping class) in the configuration file.

2 1.3 The components in the struts frame (because the ROSE tool has not been downloaded, only this picture, it illustrates a certain question, especially ActionerRors, but it doesn't contain the actionmapping, jsp, and tag library, there is time Operation replacement) The components used in the framework: ActionServlet Controller ActionClass Contains Transaction Logic ActionForm Display Module Data ActionMApping Help Controller The ActionError to indicate the operational action ActionForward to indicate the operational transfer object ActionError is used to store and recycle the error Struts tag library Mitors the Work of Development Display Hierarchy Next We look at the roles and responsibilities they play in the framework. 1.3.1 Struts Profile This is the stuff with the Struts component: struts-config.xml. Default /Web-inf/struts-config.xml. Profiles can be defined: Global forwardingMapping class Actionform Bean JDBC Data Source Configuration Global Forward Global Forwarding is used to create logical name mappings between JSP pages. The forwarding can be obtained by the instance of the calling operation map, for example: ActionMappingInstace.Findforward ("LogicalName"); global forwarding example: (I have not explained all examples, one is that the combination table can be understood, the second is the example of the example Examples from the series four, you should look at the experiment, then look at it) 3 Property Description Name Global Forward Name Path Configuring the ActionMApping ActionMapping objects with the relative path of the target URL to help flow control within the framework, which can map the request URI to the Action class and associate the Action class with the ActionForm bean. ActionServlet uses these mappings internally and transfers control to an instance of a specific Action class. All Action classes use the Perform () method to implement a specific application code, return an ActionForward object, including the target resource name of the response forwarding. For example: Property Description Path Action class relative path NAME is associated with this operation Action bean Name TYPE Connect to the full name of the Action class (available) Scope Actionform Bean scope (request or session) prefix is ​​used to match the prefix of the request parameter and the prefix for the bean property to match the request parameter to the suffix of the request parameter and the bea property suffix Attribute scope.

The fully qualified name of the class of the classname actionMapping object is org.apache.struts.Action.ActionMapping input input to the path to enter the form, pointing to the Control Unknown, which must return to the BEAN, set to True, the operation will be used as all unselected The default operation of the ActionMapping URI is set to TRUE, before calling the Perform () method on the Action object, the ActionServlet will call an actionform bean's validate () method for input check via element, which can define the logical name of the resource. This resource is the target of the Action class's response to forward. Property Description ID ClassName ActionForward class fully qualified name, default is org.apache.struts.Action.ActionForwardName Operation class Access ActionForward When the logical name path response forwarded target resource Path 4 Redirect If set to true, ActionServlet use SendRedirect () method to forward the resource configuration ActionForm Bean ActionServlet uses ActionForm to save the request parameters, these beans correspond to the name in the HTTP request parameter, the controller passes the request parameters to the ActionForm bean instance, and then this instance Transfer to the Action class. Example: Properties Description ID ID ClassName ActionForm Bean's fully qualified name, the default value is org.apache.struts. The Action.ActionformBean Name form bean is in the name of the relevant scope, this property is used to configure the fully qualified name of the bean with ActionMapping Type class to configure the JDBC data source element to define multiple data sources. Property Description ID The Id KEY Action class uses this name to find the name of the class that connects the Type to implement the JDBC interface. The following properties need the element definition, is not used in the frame 1.1 version, but you can use elements .

Example: Properties Description Desciption Data Source Description AutoCommit Data Source Create The Default Auto Update Number 5 The class used by the DRIVERCLASS data source used to Display the JDBC driver interface logintimeout database login time limit, in seconds unit Maxcount Up to the number of connections MINCOUNT MINCOUNT To create the minimum number of connections to the password database Accessing the password Readonly Create a read-only connection USER URL JDBC URL can access data sources by specifying a keyword name, such as javax.sql.datasource ("contool"); javax.sql.connection con = ds.getConnection (); 1.4 ActionServlet class frame The controller component is implemented with org.apache.struts.Action.ActionServlet class, this class is an extension of the javax.servlet.http.httpservlet class. The Struts Controller's basic feature is: 1. Intercepting the user's HTTP request 2. Map the request to the corresponding Action class, if this is the first request received by this class, the instance and coalesion will be initialized. 3. Create or discover an ActionForm bean instance (see if the configuration file is defined), then transplant the request process to bean. 4. Call the action instance's Perform () method and pass the Actioform Bean, Action Mapping object, Request, and Response objects. it. Such as: public ActionForword perform (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 5.perform returns a ActionForword object that is connected to the appropriate jsp page 1.4.1 ActionServlet ActionServlet configuration we need to declare in web.xml. And configure it to be loaded.

The following can be configured: Parameter Default Value Description Application Null Application Resource Collection Class Buffersize 4096 File Uploaded Buffer Size 6 Config /Web-inf/Struts-config.xml Profile Location and Name Content Text / HTML Default Content Type Debug 0 Program Debug Level Detail 0 Program Debug Detail Factory Null Message Resource Factory, Used Interpretation Message Resources FORMBEAN Org.Apache.Struts.Action.ActionFormBean Package Actionform Bean Information Class name Forward Org.Apache.Struts.Action.ActionForward encapsulates the name locale true of the ActionForward object information, which will store a local object mapping org.apache.struts.Action.ActionForward package ActionMapping information in a user session MaxFileSize 250M The maximum size of the upload file multipartclass org.apache.struts.Action.ActionForward Processes the NOCACHE FALSE HTTP header to be set to True, for invalid information Keywords, for invalid information keywords, returns NULL Tempdir is provided to the program for a servlet parameter to process the download file is the temporary work directory VALIDATE TRUE uses the new format profile Vallidating True to effectively analyze the configuration files, the standard servlet can meet User needs. When the URI of the first received a specific request, the ActionServlet instantiates the appropriate Action class, and the ActionServlet stores a reference in servlet in the Action class instance. When instantiated, the Action class will be temporarily stored. ActionServlet also provides some methods that use the Action class to access resources such as data sources and forwarding targets. 1.4.2 ActionServlet method ActinServlet provides a group of methods that can be used by Action objects. All information for the Struts API can be found in Struts-Documentation.war.

Dynamically add or delete these methods affect only the current instance of the application: public void addFormBean (ActionFormBean formBean) public void removeFormBean (ActionFormBean formBean) public void addForward (ActionForward actionForward) public void removeForward (ActionForward actionForward) public void addMapping (ActionMapping actionMapping ) 7 public void removeMapping (ActionMapping actionMapping) find objects by name: public ActionFormBean findFormBean (String name) public ActionForward findForward (String name) public ActionMapping findMapping (String name) to the data source: public void addDataSource (String key, dataSource ds Applicate FindataSource, we also: Use the Destroy () method to end the actionServlet Using the RELOAD () method to reload the information from the Struts profile. 1.5 ActionMapping class Related information to a specific Action to a specific Action stored in actionMApping, ActionServelt transmits ActionMApping's Perform () method, Action will use an actionMApping's Findforward () method, this method returns a specified name ActionForward, This way Action has completed local forwarding. If specific ActionForward not found, it returns a null public ActionForward findForward (String name) can be dynamically added ActionForward in the map:. Public void addForward (ActionForward forward) to return to the form bean mapping associated with: public String getName () to return Mapping Attribute Domain (Session or Request) Public String GetScope () 1.6 Action class Action class really implements the application's transaction logic, which is responsible for processing the request. After receiving the request, the ActionServlet will: select the appropriate action for this request, if necessary, create an instance of an action call an action for an action if the ActionServlet does not find a valid map, it calls the default Action class (in profile) Definitions in it). If you find the ActionServlet forward to the appropriate actionMApping class, this action uses actionMapping to find local forwarding, then get an actionMApping property. The ActionServlet also transmits the ServletRequest object or HTTPServletRequest object according to the signature of the servlet environment and the overform () method. All Action classes expand the org.apache.struts.Action.Action class, and override a perform () method defined in the class.

Two perform () method: non-treated HTTP (general) request: 8 public ActionForward perform (ActionMapping action, AcionForm form, ServletRequest request, ServletResponse response) throws IOException, ServletException HTTP requests: public ActionForward perform (ActionMapping action, AcionForm FORM, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETRESE RESPONSE) THROWS IOException, the ServleTexception Action class must program as "thread security" mode, because the controller will share the same instance to multiple simultaneous requests, corresponding, when designing the Action class Need to note: You cannot use instance or static variables to store status information for specific requests, which share global resources across requests in the same operation. If you want to access resources (such as JavaBean and session variables) need to perform in parallel access Protection, then access to synchronization 1.6.1 Action class method In addition to the Perform () method, there is also the following methods: You can get or set the area associated with the request: Public Locale getLocale (httpservletRequest request) Public void setLocale (httpservletRequest Request, Locale Locale Gets Message Resources for the application: public messageresources getResources () Checks the user clicking on the "Cancel" button on the table, if yes, returning True: public boolean iscancelled (httpservletRequest request) When an application is errors, The Action class can store an error message using the method: Public Void SaveErRors (HTTPSERVLETREQUEST, ActionerRors ERRORS) ActionError instance is used to store an error message, and this method stores an ActionError object in the error keyword's request attribute list. The JSP page can display these error messages by using the custom tag defined in the Struts tag library. We will introduce later. 1.7 Actionform class framework assumes that users create an actionform bean for each form in the application, and the framework is performed before the bean defined in the struts-config.xml file is called before calling the acting class's Perform () method. Action: In the associated keyword, it checks the user session for the Bean instance for the appropriate class. If there is no Bean available in the session, it will automatically create a new bean and add it to the user's session. For each parameter corresponding to the bean property name, the Action calls the corresponding setting method. 9 When Action Perform () is called, the latest ActionForm bean is transferred to it, and the parameter value can be used immediately. ActionForm class extension org.apache.struts.Action.Actionform class, the BEAN created by program developers can include additional properties, and ActionServlet may use reflection (allowing recycling information from loaded objects) to access it.

ActionForm class provides another means of handling errors, provides two methods: Public ActionErrors validate (ActionMappin mapping, ServletRequest request) Public ActionErrors validate (ActionMappin mapping, HttpServletRequest request) you should cover validate in their own bean in () method, And set the validate of the element in the configuration file to True. Before the ActionServlet calls the Action class, it calls validate (), if the ActionerRors returned is not null, ActinForm will store ActionerRors in the request attribute list based on the error keyword. If the returned is not NULL, and the length is greater than 0, the instance is stored in the requested attribute list according to the error key, and then the ActionServlet will be forwarded to the target pointing to the INPUT property of the configuration file element. If you need to perform a specific data validity check, it is best to do this in the Action class, not in the ActionForm class. Method reset () can be restored to the default value bean property: public void reset (ActionMapping mapping, HttpServletRequest request) public void reset (ActionMapping mapping, ServletRequest request) only typical ActionFrom bean setting attributes and reading method (getXXX), There is no way to achieve transaction logic. Only simple input check logic, the purpose of use is to store the latest data entered in the relevant form so that the same web page can be regenerated while providing a set of error messages so that the user can modify the incorrect input data. It is really checking data validity to check the Action class or the appropriate transaction logic bean. 1.8 ActionForWard class 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 findforward (): ActionServlet obtaining a global forwardingmAppin instance is transmitted to the Perform () method according to the name, and find a local forwarding according to the name The other is to call the following constructor to create an example: public actionforward () public actionforward (String path) Public ActionForward (String Path, Boolean Redirect) 10 1.9 Error handling Struts provides two classes to handle errors : ActionerRors and ActionError, they expand org.apache.struts.Action. ActionerRORS saves a collection of ActionError objects, each represents an independent error message. Each ActionError contains a keyword, which is mapped to the error message stored in the resource file, and this resource file is specified in the ActionServlet initialization parameter.

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

New Post(0)