Struts Get started with articles, easy to understand (reproduced)

xiaoxiao2021-03-06  98

This chapter explains a simple Struts application example HelloApp application, which can help readers quickly get started and obtain basic experience in developing Struts applications. The function is very simple, accepts "Hello ". Developing HelloApp applications involving the following:

l Analyze application needs

l Use the Struts framework based on the MVC design mode to the app.

l Create a view component, including HTML form (Hello.jsp) and Actionform Bean (Helloform.java)

l Create an Application.properties resource file

l Data verification, including form verification and business logic verification

l Create a controller component: HelloAction.java

l Create a model component: Personbean.java

l Create a Java file containing constant data shared by each module: constants.java

l Create a configuration file: Web.xml and Struts-Config.xml

l Compile, release, and run HelloApp applications

2.1 Analyze the needs of HelloApp applications

When developing applications, first start from analysis requirements, enumerating the various functions of the application, and restriction conditions. The need for HelloApp applications is very simple, including the following requirements:

l Accept your name , then return the string "Hello !"

l If the user does not enter the name, submit the form, will return the error message, prompting the user to enter the name.

l If the user enters a name "MONSTER", it will return the error message and refuse to greet "Monster".

l In order to demonstrate the function of the model component, this application uses model components to save the name of the user.

2.2 Application Struts Framework

The Struts framework is applied to the HelloApp application. The Struts framework can easily quickly divide a complex application into models, views, and controller components, while Struts's configuration files Struts-config.xml can be flexible to assemble these components, simplify the development process.

The following is the composition of each module of the HelloApp application:

The model includes a JavaBean component Personbean, which has a username property represents the name entered by the user. It provides a GET / SET method that is used to read and set the username property, and it also provides a Save () method, which is responsible for saving the username property into a persistent storage system such as a database or file system. For more complex web applications, the JavaBean component can serve as a front-end component of the EJB or web service.

The view includes a JSP file hello.jsp, which provides a user interface that accepts the name of the user. The view also includes an actionform bean that stores form data and performs a form authentication. If the user does not enter the name, submit the form, will return the error message.

l The controller includes an Action class HelloAction that completes three tasks: 1. Error messages will be returned if the business logic verification is performed. Call the Save () method of the model component Personbean, save the name of the user; 3. Decide to return the appropriate view components to the user. In addition to creating models, views, and controller components, you also need to create Struts configuration file struts-config.xml, which can assemble these components to make them work. In addition, you also need to create a configuration file for the entire web application. Web.xml.

2.3 Creating view components

In this case, the view includes two components:

l A JSP file: Hello.jsp

l An Actionform Bean: Helloform Bean

The following describes how to create these two components.

2.3.1

Create a JSP file

Hello.jsp Provides a user interface that accepts the name of the user. In addition, all output results of this web application are also displayed by hello.jsp. Figure 2-1 shows the web page provided by Hello.jsp.

Figure 2-1 Hello.jsp of the web

In Figure 2-1, after entering the name "weiqin", press the submission form, this app will return "Hello Weiqin!", See Figure 2-2.

Figure 2-2 Hello.JSP accepts the web page returned to the user after entering

Routine 2-1 is the source code for the Hello.jsp file.

Routines 2-1 Hello.jsp

<% @ page contenttype = "text / html; charset = uTF-8" Language = "java"%>

<% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%>

<bean: message key = "Hello.jsp.title" /> </ title></p> <p><HTML: BASE /></p> <p></ hEAD></p> <p><body bgcolor = "white"> <p></p> <p><H2> <bean: Message Key = "Hello.jsp.page.Heading" /> </ h2> <p></p> <p><html: errors /> <p></p> <p><logic: present name = "Personbean" scope = "request"></p> <p><H2></p> <p><bean: message key = "Hello.jsp.page.hello" /></p> <p><bean: write name = "personbean" property = "username" />! <p> </ h2></p> <p></ logic: present></p> <p><html: form action = "/ helloworld.do" FOCUS = "Username"></p> <p><bean: message key = "Hello.jsp.prompt.Person" /></p> <p><html: text protety = "username" size = "16" maxlength = "16" /> <br></p> <p><html: Submit property = "submit" value = "submit" /></p> <p><html: reset /></p> <p></ html: form> <br></p> <p><html: img Page = "/ struts-power.gif" alt = "powerd by struts" /></p> <p></ body></p> <p></ html: html></p> <p>The above Struts framework-based JSP file has the following features:</p> <p>l No Java program code</p> <p>l Using many Struts's customized tags, such as <HTML: Form> and <Logic: Present> tags</p> <p>l There is no direct provision of text content, which is the <bean: Message> tag, and the text content that is output to the web page is generated by the <bean: Message> tag. E.g:</p> <p><bean: message key = "Hello.jsp.prompt.Person" /></p> <p>The Struts Customization Tag is a link between contact view components and other components in the Struts framework. These tags can access or display data from the controller and model components. In this book, Chapter 12 to 16, specifically introduce the use of Struts tags, this section briefly introduces several important Struts tags.</p> <p>Hello.jsp starts a few lines for declaration and loading struts tags:</p> <p><% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%></p> <p><% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%></p> <p><% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%></p> <p>The above code indicates that the JSP file uses the Struts Bean, HTML, and Logic tag libraries, which is the standard JSP syntax loaded with the custom label library.</p> <p>The tags from the Struts HTML tag library are used in Hello.jsp, including <HTML: ERRORS>, <HTML: Form>, <HTML: Text>:</p> <p>l <html: Errors>: An error message generated by other components in the Struts framework.</p> <p>l <html: form>: Used to create an HTML form, which can associate the field of the HTML form and the properties of the ActionForm bean.</p> <p>l <html: text>: This tag is a sub-tag of <HTML: Form> to create a text box for an HTML form. It is associated with the properties of the Actionform Bean. Two labels from the Struts Bean label library are used in Hello.jsps, and <bean: write>:</p> <p>l <bean: message>: Used to output a localized text content, its key property specifies message key, and message key matching text content comes from special resource bundle, see Chapter 9 of this book on the concept of Resource Bundle ( Internationalization of Struts Application).</p> <p>l <bean: write>: Used to output the properties of JavaBeans. In this example, it is used to output the username property value of the Personbean object:</p> <p><bean: Write Name = "Personbean" property = "username" /></p> <p>Hello.jsp uses the <Logic: Present> tab from the Struts Logic tag library. <logic: present> Tags are used to determine whether JavaBean exists within a specific range, only when JavaBean exists: the contents of the label body are executed:</p> <p><logic: present name = "Personbean" scope = "request"></p> <p><H2></p> <p>Hello <bean: write name = "personbean" property = "username" />! <P></p> <p></ h2></p> <p></ logic: present></p> <p>In this example, the <logic: present> label is used to determine if there is a PersonBean object in the request range, if there is, the PersonBean's username property value is output. The <logic: present> tag is the <logic: notpresent> tag, which means that only the contents of the tag body only when JavaBean does not exist within a specific range.</p> <p>2.3.2</p> <p>Create a message resource file</p> <p>Hello.jsp Use the <bean: Message> tab to output text content. These texts come from Resource Bundle, each corresponding to one or more localized message resource files, the resource file in this example is Application.properties, routine 2-2 is the content of the message resource file.</p> <p>Routine 2-2 Application.properties file</p> <p>#Application resources for the "Hello" Sample Application</p> <p>Hello.jsp.title = Hello - A First Struts Program</p> <p>Hello.jsp.page.Heading = Hello World! A First Struts Application</p> <p>Hello.jsp.prompt.Person = please enter a username to say hello to:</p> <p>Hello.jsp.page.hello = Hello</p> <p>#Validation and error message for helloform.java and helloaction.java</p> <p>Hello.dont.talk.to.monster = we don't want !!! hello.no.username. error = please enter a <i> username </ i> to say hello to!</p> <p>The above file stores data in the form of "Message Key / Message Text", and the "#" in the file is a comment line. For the following JSP code:</p> <p><bean: message key = "Hello.jsp.title" /></p> <p><bean: Message> The key attribute of the label is "Hello.jsp.tilte", and the contents matching in the resource bundle are:</p> <p>Hello.jsp.title = Hello - A First Struts Program</p> <p>Therefore, the above <bean: Message> tab will output "Hello - A First Struts Program" to the web.</p> <p>2.3.3</p> <p>Create an Actionform Bean</p> <p>When the user submits an HTML form, the Struts framework automatically assembles the form data into the Actionform Bean. The properties in the ActionForm bean are in one or one in the field in the HTML form. Actionform Bean also provides a data verification method and a method of resetting the property as a default. The ActionForm class defined in the Struts framework is abstract, you must create its subclass in your application to store specific HTML form data. Routines 2-3 is the source program of Helloform.java, which is used to process form data in Hello.jsp.</p> <p>Routines 2-3 Helloform.java</p> <p>Package hello;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import org.apache.struts.action.actionMessage;</p> <p>Import org.apache.struts.Action.Actionerro;</p> <p>Import org.apache.struts.Action.actionform;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Public Final Class Helloform Extends Actionform {</p> <p>Private string username = null;</p> <p>Public string getUsername () {</p> <p>Return (this.username);</p> <p>}</p> <p>Public void setusername (String username) {</p> <p>THIS.USERNAME = UserName;</p> <p>}</p> <p>/ **</p> <p>* RESET All Properties to Their Default VALUES.</p> <p>* /</p> <p>Public void reset (actionMapping mapping, httpservletRequest request) {</p> <p>THIS.USERNAME = NULL;</p> <p>}</p> <p>/ **</p> <p>* Validate The Properties Posted in This Request. If Validation Errors Are</p> <p>* Found, return AN <code> ActionerRors </ code> Object Containing The Errors.</p> <p>* If no validation errors occur, return <code> null </ code> or an empty</p> <p>* <code> ActionerRors </ code> object.</p> <p>* /</p> <p>Public ActionerRors Validate (ActionMapping Mapping,</p> <p>HttpservletRequest request) {</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>IF ((username == null) || (username.length () <1))</p> <p>Errors.Add ("UserName", New ActionMessage ("Hello.No.username.Error");</p> <p>Return Errors;</p> <p>}</p> <p>}</p> <p>As can be seen from the above code, Actionform Bean is substantially a JavaBean, but it has two special methods in addition to JavaBean conventional methods:</p> <p>l Validate (): Used for Form Verification.</p> <p>l Reset (): Reset the property to the default value.</p> <p>2.3.4</p> <p>data verification</p> <p>Almost all applications with user interaction require data verification, while designing and developing a perfect data verification mechanism often takes time. Fortunately, the STRUTS framework provides ready-made, easy to use data verification. The data verification of the Struts frame can be divided into two types: form verification and business logic verification, in this case, they are used in the following occasions:</p> <p>l Form Verification: If the user does not enter the name in the form, submit a form, generate a form verification error.</p> <p>l Business Logic Verification: If the user entered in the form, according to the business rules of this application, it is not allowed to greet "Monster", so it will generate a business logic error.</p> <p>The first type of verification, that is, the form verification is processed by the Actionform Bean. In this example, the validate () method of Helloform.java is responsible for completing this task:</p> <p>Public ActionerRors Validate (ActionMapping Mapping,</p> <p>HttpservletRequest request) {</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>IF ((username == null) || (username.length () <1))</p> <p>Errors.Add ("UserName", New ActionMessage ("Hello.No.username.Error");</p> <p>Return Errors;</p> <p>}</p> <p>}</p> <p>When the user submits an HTML form, the Struts framework automatically assembles the form data into the Actionform Bean. The next Struts framework automatically invokes the Validate () method of the Actionform Bean for forms. If the Validate () method returned to the ActionerRors object as null, or does not contain any actionMessage objects, it means no errors, data verification is passed. If the actionMessage object is included in the ActionerRORS, you represent an authentication error, and the Struts framework saves the ActionerRors object to the REQUEST range, then forward the request to the appropriate view component, and the view component via <HTML: Errors> tab puts the request within the REQUEST range The error message contained in the ActionerRORS object is displayed, prompting the user to modify the error.</p> <p>In the early versions of Struts, use the ActionError class to represent an error message, the ActionError class is the subclass of ActionMessage. Struts1.2 will discard Actionerror, unify the ActionMessage class to represent normal or error messages. The second type of verification, that is, business logic verification, by Action to handle, see this chapter</p> <p>2.4.3</p> <p>Section.</p> <p>2.4 Creating a controller component</p> <p>The controller component includes an ActionServlet class and an Action class. The ActionServlet class is coming from the Struts frame, which is the control hub of the entire Struts framework, usually does not need to be expanded. The STRUTS framework provides an Action class for extended, which is used to handle specific HTTP requests, routines 2-4 for the source program of the HelloAction class.</p> <p>Routines 2-4 HelloAction.java</p> <p>Package hello;</p> <p>Import javax.servlet.RequestDispatcher;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpsession;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import org.apache.struts.Action.action;</p> <p>Import org.apache.struts.action.actionMessage;</p> <p>Import org.apache.struts.Action.actionMessages;</p> <p>Import org.apache.struts.Action.actionform;</p> <p>Import org.apache.struts.Action.actionForward;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Import org.apache.struts.util.MessageResources;</p> <p>Public final class helloaction extends action {</p> <p>/ **</p> <p>* Process The Specified Http Request, and Create The Corresponding HTTP</p> <p>* Response (or Forward to another Web Component That Will Create IT).</p> <p>* Return AN <code> Actionforward </ code> Instance Describing Where and how</p> <p>* Control SHOULD BE Forwarded, or <code> Null </ code> if The Response HAS</p> <p>* Already Been Completed.</p> <p>* /</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>Throws exception {</p> <p>// Thase "Messages" come from the applicationResources.properties file</p> <p>MessageResources Messages = GetResources (Request);</p> <p>/ *</p> <p>* Validate The Request Parameters Specified by The User</p> <p>* Note: Basic Field Validation Done in Helloform.Java * Business Logic Validation Done in HelloAction.java</p> <p>* /</p> <p>ActionMESSAGES ERRORS = New ActionMessages ();</p> <p>String username = (helloform) .getusername ();</p> <p>String Badusername = "monster";</p> <p>IF (username.equalsignorecase (badusername) {</p> <p>Errors.Add ("UserName", New ActionMessage ("Hello.dont.talk.to.monster",</p> <p>Badusername);</p> <p>SaveerRors (Request, Errors);</p> <p>Return (maping.getInput ())));</p> <p>}</p> <p>/ *</p> <p>* Having received and validated the data submitted</p> <p>* From the view, We now Update The Model</p> <p>* /</p> <p>Personbean PB = New Personbean ();</p> <p>Pb.setUsername (username);</p> <p>Pb.savetopistentstore ();</p> <p>/ *</p> <p>* If The Model of View Components It Depunded on the model</p> <p>* (or some other) status, we'd make the decision here as to which</p> <p>* To Display. in this case, There is Only ONE VIEW Component.</p> <p>*</p> <p>* WE Pass Data To the View Components by Setting Them As Attributes</p> <p>* in The Page, Request, Session Or Servlet CONTEXT. IN THIS Case, The</p> <p>* MOST Appropriate Scoping Is The "Request" Context Since The Data</p> <p>* Will NOT Be Neaded After the View is generated.</p> <p>*</p> <p>* Constants.Person_Key Provides a KEY Accessible by Both The</p> <p>* Controller Component (I.e. this class) and the view component</p> <p>* (i.e. The JSP File We Forward to).</p> <p>* /</p> <p>Request.setttribute (constants.Person_Key, PB);</p> <p>// Remove the form bean - Don't Need to Carry Values ​​Forward</p> <p>Request.Removettribute (mapping.getattribute ());</p> <p>// forward control to the specified surcess URI</p> <p>Return (Mapping.Findforward ("Sayhello");</p> <p>}</p> <p>}</p> <p>HelloAction.java is the most complex program in this application, following step by step to explain its working mechanisms and processes.</p> <p>2.4.1 a</p> <p>Working mechanism for CTION class</p> <p>All Action classes are subclasses of org.apache.struts.Action.Action. The Action subclass should cover the parent class's Execute () method. When the ActionForm bean is created, the STRUTS framework is called the Execute () method of the Action class after the form verification is passed. The definition of the execute () method is as follows: Public actionforward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>HttpservletResponse response) THROWS IOEXCEPTION, SERVLETEXCEPTION;</p> <p>The execute () method contains the following parameters:</p> <p>l actionMApping: The configuration information of this action is included, and the <action> element in the struts-config.xml file is corresponding.</p> <p>l Actionform: The user's form data is included. When the Struts framework calls the execute () method, the data in the ActionForm has passed form validation.</p> <p>l httpservletRequest: Current HTTP Request Object</p> <p>l httpservletResponse: Current HTTP Response Object</p> <p>The Execute () method of the Action class returns an ActionForWard object that contains request forwarding path information.</p> <p>2.4.2</p> <p>Localization text in encapsulation in MessageResources</p> <p>In this example, the Execute () method of the Action class first gets the MessageResources object:</p> <p>MessageResources Messages = GetResources (Request);</p> <p>The getResources (httpservletRequest request) method is defined in the Action class, which returns the current default MessageResources object, which encapsulates the text content in the Resource Bundle. Next Action class can access text content through the MessageResources object. For example, if you want to read the text content corresponding to the message key to "Hello.jsp.title", you can call the MessageResources class's getMessage (String Key) method:</p> <p>String Title = Messages.getMessage ("Hello.jsp.title");</p> <p>2.4.3</p> <p>Business logic verification</p> <p>Next, the execute () method of the Action class performs business logic verification:</p> <p>ActionMESSAGES ERRORS = New ActionMessages ();</p> <p>String username = (helloform) .getusername ();</p> <p>String Badusername = "monster";</p> <p>IF (username.equalsignorecase (badusername) {</p> <p>Errors.Add ("Username", New ActionMessage ("Hello.dont.talk.to.monster", BaduserName));</p> <p>SaveerRors (Request, Errors);</p> <p>Return (maping.getInput ())));</p> <p>}</p> <p>If the user entered the name "MONSTER", the ActionMessage object containing the error message is created, and the ActionMessage object is saved to the ActionMessages object. Next, call the SaveErRors () method defined in the Action base class, which is responsible for saving the ActionMessages object to the REQUEST range. Finally, return the ActionForward object, and the Struts framework forwards the request to the appropriate view component according to the forwarding information contained in the ActionForward object, and the view component is displayed by <html: errors> tab to display the error message contained in the ActionMessages object in the request range, prompting users. correct mistakes. in</p> <p>2.3.4</p> <p>The section also refers to the ActionerrorS object, Figure 2-3 shows the class box diagram of ActionMessages, ActionerRRORS, ActionMessage, and ActionError classes. ActionerRORS Inherits ActionMessages, ActionError Inherited ActionMessage, ActionMessages and ActionMessage are aggregated relationships, that is, multiple ActionMessage objects in an ActionMessages object.</p> <p>Figure 2-3 ActionMessages, ActionerRors, ActionMessage, and ActionError class box diagram</p> <p>Form verification is usually only simplified syntax and formatting of data entered by the user, while business logic verification will make data more complex verification. In many cases, it is necessary to intervene in model components to complete business logic verification.</p> <p>2.4.4</p> <p>Access model components</p> <p>Next, the HelloAction class creates a model component PersonBean object and calls its SavetoPersister () method to save the username property:</p> <p>Personbean PB = New Personbean ();</p> <p>Pb.setUsername (username);</p> <p>Pb.savetopistentstore ();</p> <p>This example only provides an example of a simple Action Access Model Component. In practical applications, the Action class will access model components to complete more complex features, such as:</p> <p>l Read data from the model assembly for view components.</p> <p>l and multiple model components interact</p> <p>l Determine the return to which view component is decided based on the information obtained from the model assembly.</p> <p>2.4.5</p> <p>Pass data toward view components</p> <p>The Action class stores the data within the Request or Session range to deliver information to the view component. The following is the code to pass the data to the view component:</p> <p>Request.setttribute (constants.Person_Key, PB);</p> <p>// Remove the form bean - Don't Need to Carry Values ​​Forward</p> <p>Request.Removettribute (mapping.getattribute ());</p> <p>The above code completes two things:</p> <p>l Save the PersonBean object within the request range.</p> <p>l Delete an Actionform Bean from the request range. Since subsequent request forwarding destination components no longer need Helloform Beans, it can be deleted.</p> <p>2.4.6</p> <p>Forward HTTP requests to the right view component</p> <p>Finally, the Action class forwards the process to the appropriate view components.</p> <p>// forward control to the specified surcess URI</p> <p>Return (Mapping.FindForward ("Sayhello"); 2.5 Creating Model Components</p> <p>In the previous section, the Action class will access the model components. In this example, the model assembly is a JavaBean: Personbean. Routines 2-5 are the source code of Personbean:</p> <p>Routines 2-5 Personbean.java</p> <p>Package hello;</p> <p>Public class persons {</p> <p>Private string username = null;</p> <p>Public string getUsername () {</p> <p>Return this.username;</p> <p>}</p> <p>Public void setusername (String username) {</p> <p>THIS.USERNAME = UserName;</p> <p>}</p> <p>/ **</p> <p>* This is a stub method That Would Be buy for the model to save</p> <p>* The Information Submitted to a Persistent Store. in this Sample</p> <p>* Application IT is not used.</p> <p>* /</p> <p>Public void savetopersistentstore () {</p> <p>/ *</p> <p>* This is a stub method That Might Be buy to save the person's</p> <p>* Name to a Persistent Store (i.e. Database) IF this were a real applibility.</p> <p>*</p> <p>* The Actual Business Operations That Would EXIST WITHIN A MODEL</p> <p>* Component Would Depend Upon The Requirements of the Application.</p> <p>* /</p> <p>}</p> <p>}</p> <p>Personbean is a very simple JavaBean that includes a username property, as well as related GET / SET methods. In addition, it has a business method SaveToPersisterStore (). This method is not truly realized in this example. In practical applications, this method can be used to save JavaBean properties in a persistent storage system, such as a database or file system.</p> <p>Through this simple example, the reader can further understand a large advantage of using the model assembly in the Struts framework, which separates the other parts of the business logic, and can improve the flexibility, reusability and scalable and scalable of the entire application. Sex. If the implementation of the model component changes, for example, the property of the JavaBean is saved in the mysql database, then changed to the Oracle database, at which time the Action class does not need to make any changes. Not only that, even if the model component is changed to EJB by JavaBean, running on a remote application server or there will be any impact on the Action class.</p> <p>2.6 Creating a Java file that stores the flow</p> <p>according to</p> <p>2.4.5</p> <p>The data between the request range is shared between the section, the HelloAction class, and view components through the httpservletRibute () and getAttribute () methods. Let's take a look at the details of the HTTPSERVLETREQUEST's setAttribute () method.</p> <p>When the HTTPSERVLETREQUEST's setAttribute () method is sent to Hello.jsp, you need to provide a property known as "Personbean": KEY:</p> <p>Request.setttribute ("Personbean", PB);</p> <p>Hello.JSP reads the Personbean object by this property key named "Personbean": <logic: present name = "personbean" scope = "request"></p> <p><H2></p> <p>Hello <bean: write name = "personbean" property = "username" />! <P></p> <p></ h2></p> <p></ logic: present></p> <p>For Struts applications, it is advocated to define these properties key constants in a Java file constants.java, routines 2-6 show its source program.</p> <p>Routines 2-6 Constants.java</p> <p>Package hello;</p> <p>Public Final Class Constants {</p> <p>/ **</p> <p>* The Application Scope Attribute Under Which Our User Database</p> <p>* is store</p> <p>* /</p> <p>Public static final string person_key = "personbean";</p> <p>}</p> <p>In this way, the HelloAction class can call the httpservletRequest's setAttribute () method as follows:</p> <p>Request.setttribute (constants.Person_Key, PB);</p> <p>Define some constants in constants.java to improve the independence of the Action class, when the property Key constant value changes, only need to modify the constants.java file and do not need to modify the Action class.</p> <p>In addition, in this example, the PersonBean object is saved in the HTTPServletRequest object. For other actual web applications, you can also save the JavaBean object in the httpsession object as needed.</p> <p>2.7 Creating a configuration file</p> <p>2.7.1</p> <p>Create a web application configuration file</p> <p>For Struts applications, its configuration file Web.xml should configure the ActionServlet class. In addition, the Struts tag library used by the web application. This example uses three label libraries: struts bean, struts HTML and STRUTS Logic tag library. Routines 2-7 is the source code of web.xml.</p> <p>Routines 2-7 Web.xml</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! DocType web-app</p> <p>PUBLIC "- // Sun microsystems, Inc.//dtd Web Application 2.2 // en"</p> <p>"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"></p> <p><web-app></p> <p><Display-Name> HelloApp Struts Application </ display-name></p> <p><! - Standard Action Servlet Configuration -></p> <p><servlet></p> <p><servlet-name> Action </ servlet-name></p> <p><servlet-class> org.apache.struts.Action.ActionServlet </ servlet-class></p> <p><init-param></p> <p><param-name> config </ param-name> <param-value> /Web-inf/struts-config.xml </ param-value></p> <p></ init-param></p> <p><Load-on-Startup> 2 </ loading-on-startup></p> <p></ servlet></p> <p><! - standard action servlet mapping -></p> <p><servlet-mapping></p> <p><servlet-name> Action </ servlet-name></p> <p><url-pattern> *. do </ url-pattern></p> <p></ servlet-maping></p> <p><! - the usual welcome file list -></p> <p><Welcome-file-list></p> <p><Welcome-File> Hello.jsp </ welcome-file></p> <p></ welcome-file-list></p> <p><! - struts tag library descriptors -></p> <p><taglib></p> <p><taglib-uri> /web-inf/struts-bean.tld </ taglib-uri></p> <p><taglib-location> /web-inf/struts-bean.tld </ taglib-location></p> <p></ taglib></p> <p><taglib></p> <p><taglib-uri> /web-inf/struts-html.tld </ taglib-uri></p> <p><taglib-location> /web-inf/struts-html.tld </ taglib-location></p> <p></ taglib></p> <p><taglib></p> <p><taglib-uri> /web-inf/struts-logic.tld </ taglib-uri></p> <p><taglib-location> /web-inf/struts-logic.tld </ taglib-location></p> <p></ taglib></p> <p></ web-app></p> <p>2.7.2</p> <p>Create a configuration file for the Struts framework</p> <p>As mentioned earlier, the Struts framework allows applications to be divided into multiple components and increase development speed. The configuration files for the Struts framework Struts-config.xml can assemble these components and determine how to use them. Routines 2-8 are the source code for the struts-config.xml file for the HelloApp application.</p> <p>Routines 2-8 Struts-Config.xml</p> <p><? Xml Version = "1.0" encoding = "ISO-8859-1"?></p> <p><! DocType struts-config public PUBLIC</p> <p>"- // Apache Software Foundation // DTD Struts Configuration 1.1 // en"</p> <p>"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"></p> <p><! -</p> <p>This is the struts configuration file for the "Hello!" Sample Application</p> <p>-></p> <p><struts-config></p> <p><! - =========================================== -> <form-beans></p> <p><form-bean name = "Helloform" type = "Hello.Helloform" /></p> <p></ form-beans></p> <p><! - ================================================= -></p> <p><action-mappings></p> <p><! - Say Hello! -></p> <p><action path = "/ helloworld"</p> <p>TYPE = "Hello.HelloAction"</p> <p>Name = "Helloform"</p> <p>Scope = "request"</p> <p>Validate = "True"</p> <p>INPUT = "/Hello.jsp"</p> <p>></p> <p><forward name = "Sayhello" Path = "/ hello.jsp" /></p> <p></ action></p> <p></ action-mappings></p> <p><! - ==========Message resources definitions ============================ -></p> <p><message-resources parameter = "hello.application" /></p> <p></ Struts-Config></p> <p>The above code is configured to HelloApp Applications Helloform, HelloAction, and message resource files. First, an Actionform Bean is configured with the <form-bean> element, called Helloform, which corresponds to Hello.Helloform:</p> <p><form-bean name = "Helloform" type = "Hello.Helloform" /></p> <p>An Action component is configured by <action> element:</p> <p><action path = "/ helloworld"</p> <p>TYPE = "Hello.HelloAction"</p> <p>Name = "Helloform"</p> <p>Scope = "request"</p> <p>Validate = "True"</p> <p>INPUT = "/Hello.jsp"</p> <p>></p> <p><forward name = "Sayhello" Path = "/ hello.jsp" /></p> <p></ action></p> <p><action> Element PATH attribute Specifies the path to the Action, the Type property specifies the full class name of the action, the Name property specifies the actionform bean that needs to be passed to the action, the scope property specifies the range of the ActionForm Bean, the Validate property specifies whether to perform form validation The Input property specifies the forwarding path when the form is verified. The <action> element also includes a <forward> sub-element that defines a request forwarding path.</p> <p>The <action> element in this example is configured with the HelloAction component. The corresponding class is Hello.HelloAction, requesting the access path to "HelloWorld", when the Action class is called, the Struts framework should pass the Helloform Bean that already contains form data to it. . Helloform Beans are stored in the Request range and table verification should be performed before calling the Action class. If the form verification fails, the request will be forwarded to the page hello.jsp receiving the user entered, allowing the user to correct errors.</p> <p>The struts-config.xml file finally defines a resource bundle through the <message-resources> element:</p> <p><message-resources parameter = "hello.application" /></p> <p><Message-Resources> Element Parameter property Specifies the message resource file used by Resource Bundle. In this example, the Parameter property is "Hello.application", indicating that the message resource file is named "Application.properties", which is the WEB-INF / CLASS / HELLO / Application.properties.</p> <p>2.8 Publish and run HelloApp applications</p> <p>HelloApp Applications as Java web applications, its directory structure should comply with SUN's Java web application specification, in addition, due to the HelloApp application uses the Struts framework, there should be a Struts framework to describe the JAR file and label library description file TLD file. Contain. Access http://jakarta.apache.org/builds, you can download the latest Struts package, decompress the Struts compressed file, provide the JAR file required for the Struts framework in its lib subdirectory:</p> <p>l Commons-beanutils.jar</p> <p>l Commons-Collects.jar</p> <p>l Commons-Digester.jar</p> <p>l Commons-fileupload.jar</p> <p>l commons-logging.jar</p> <p>l Commons-Validator.jar</p> <p>l jakarta-orom.jar</p> <p>l struts.jar</p> <p>All struts tag library description TLD files are also available in the lib subdirectory of the Struts package:</p> <p>l struts-bean.tldl struts-html.tld</p> <p>l struts-logic.tld</p> <p>l struts-nested.tld</p> <p>l struts-tiles.tld</p> <p>Figure 2-4 shows the directory structure of the HelloApp application.</p> <p>Figure 2-4 Directory structure of HelloApp</p> <p>The Java source file for HelloApp is located in the HelloApp / src directory. When compiling these Java source files, the Servlet API's JAR file and the struts.jar file are added to the classPath. If the Tomcat server is installed locally, it is assumed that the root directory of Tomcat is <catalina_home>, servlet-Api.jar files are provided in the <catalina_home> / circume.</p> <p>All source files for the application are provided in the Sourcecode / HelloApp / Version1 / HelloApp directory of this book. Just copy the entire HelloApp subdirectory to <Catalina_Home> / WebAPPS, you can publish this application according to the open directory structure.</p> <p>If the HelloApp application is completed, enter the product release phase, you should package the entire web application as a WAR file, and release it. In this example, you can also publish a HelloApp application on the Tomcat server as follows.</p> <p>(1) Go to the root directory of the HelloApp application under DOS.</p> <p>(2) Pack the entire web application as a HelloApp.war file, the command is as follows:</p> <p>JAR CVF HelloApp.war *. *</p> <p>(3) Copy the HelloApp.war file to the <catalina_home> / webApps directory.</p> <p>(4) Start the Tomcat server. When the Tomcat server is started, all WAR files in the WebApps directory are automatically expanded to an open directory structure. So after the server starts, it will find the server to expand HelloApp.war to the <catalina_home> / webApps / helloApp directory.</p> <p>(5) Access http: // localhost: 8080 / helloApp / hello.jsp by browser.</p> <p>2.8.1</p> <p>The server is loaded with Hello.JSP</p> <p>After successfully released HelloApp applications on Tomcat servers, access http: // localhost: 8080 / helloApp / hello.jsp, you will see the web page shown in Figure 2-5. The process of loading the Hello.jsp web page is as follows.</p> <p>(1) <bean: Message> Tag Reads text from Resource Bundle and outputs it onto the web.</p> <p>(2) <HTML: Form> Tags Find Helloform Bean in the Request range. If such an instance exists, assign the username attribute in the Helloform object to the UserName text box for the HTML form. This operation is ignored because there is no Helloform object in this time.</p> <p>(3) Present the view of Hello.jsp to the customer.</p> <p>Figure 2-5 Direct access to Hello.Jsp output web pages</p> <p>2.8.2</p> <p>Form verification process</p> <p>On the Hello.jsp page, do not enter your name, click the [Submit] button directly, you will see the web page shown in Figure 2-6.</p> <p>Figure 2-6 Form verification failed Hello.jsp page</p> <p>When the customer submits the Helloform form, the request path is "/helloWorld.do":<html:form action =" / helloworld.do "FOCUS =" Username "></p> <p>The server-side execution form verification process is as follows.</p> <p>(1) Servlet container looks for <servern> attributes in the web.xml file to "* .do" <servlet-mapping> element:</p> <p><servlet-mapping></p> <p><servlet-name> Action </ servlet-name></p> <p><url-pattern> *. do </ url-pattern></p> <p></ servlet-maping></p> <p>(2) The servlet container is based on the <servlet-name> property of the <servlet-mapping> element, "Action", looking for the matching <servlet> element in the web.xml file:</p> <p><servlet></p> <p><servlet-name> Action </ servlet-name></p> <p><servlet-class> org.apache.struts.Action.ActionServlet </ servlet-class></p> <p></ servlet></p> <p>(3) The servlet container forwards the request to the ActionServlet specified above the <servlet> element, and the ActionServlet retrieves the Path property to "/ helloworld" in the Struts configuration file in accordance with the user request path "/ HelloWorld.do":</p> <p><action path = "/ helloworld"</p> <p>TYPE = "Hello.HelloAction"</p> <p>Name = "Helloform"</p> <p>Scope = "request"</p> <p>Validate = "True"</p> <p>INPUT = "/Hello.jsp"</p> <p>></p> <p><forward name = "Sayhello" Path = "/ hello.jsp" /></p> <p></ action></p> <p>More specifically, ActionServlet retrieves an actionMApping object instead of directly accessing the <action> element in the Struts configuration file. Because the Struts configuration file is loaded when the ActionServlet is initialized, the various configuration information is saved in an instance of the corresponding configuration class, such as the configuration information of the <Action> element stores in the actionMApping object.</p> <p>(4) ActionServlet Creates a Helloform object according to the Name property of the <action> element, passes the form data submitted to the Helloform object, and then saves the Helloform object within the request range specified by the Scope property of the <action> element.</p> <p>(5) Due to the value of the value of the <action> element to true, the ActionServlet calls the validate () method of the Helloform object to perform form validation:</p> <p>Public ActionerRors Validate (ActionMapping Mapping, httpservletRequest Request) {</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>IF ((username == null) || (username.length () <1))</p> <p>Errors.Add ("UserName", New ActionMessage ("Hello.No.username.Error");</p> <p>Return Errors;</p> <p>}</p> <p>(6) The validate () method of the Helloform object returns an ActionerRors object, which contains an actionMessage object, and the error message is encapsulated in this actionMessage object, and the message is "Hello.username.Error", and the value is in the resource bundle Message text is:</p> <p>Hello.no.username. error = please enter a <i> username </ i> to say hello to!</p> <p>(7) ActionServlet The ActionerRors object package returned by Helloform has a request range, and then forwards the customer request to hello.jsp according to the <action> element INPUT attribute.</p> <p>(8) Hello.jsp <HTML: Errors> Tag Reads an ActionerRors object from the request range, and then read the ActionMessage object from the ActionerRORS object, display the error message it contains on the web.</p> <p>2.8.3</p> <p>Logic verification failure process</p> <p>Next, enter the name "MONSTER" in the HLLO.JSP HTML form, then click the [Submit] button. The verification process is as follows when the server responds to the customer request.</p> <p>(1) Repeat</p> <p>2.8.2</p> <p>Steps 1 to 4 of the section.</p> <p>(2) ActionServlet calls the validate () method of the Helloform object, this time the Validate () method is not included in the ActionerRors object, which means that the form is successful.</p> <p>(3) ActionServlet finds if the HelloAction instance exists, if there is no existence, create an instance. Then call the HelloAction's Execute () method.</p> <p>(4) HelloAction's Execute () method first performs logic verification, because there is no logic verification, create an actionMessage object, this actionMessage object encapsulates the error message, the message key is "Hello.dont.talk.to.monster", Message text with the value in Resource Bundle is:</p> <p>Hello.dont.talk.to.monster = we don't want to say hello to monster !!!</p> <p>The execute () method saves the ActionMessage object in the ActionMessages object and store the ActionMessages object within the request range. Finally returns an ActionForward object that includes the INPUT property specified by the request forwarding path for the <action> element.</p> <p>The following is the code for logic verification in the execute () method:</p> <p>ActionMESSAGES ERRORS = New ActionMessages ();</p> <p>String username = (helloform) .getusername ();</p> <p>String Badusername = "monster";</p> <p>IF (username.equalsignorecase (badusername) {</p> <p>Errors.Add ("Username", New ActionMessage ("Hello.dont.talk.to.monster", BaduserName));</p> <p>SaveerRors (Request, Errors);</p> <p>Return (maping.getInput ())));</p> <p>}</p> <p>(5) ActionServlet is forwarded to hello.jsp based on the ActionForWard object returned by HelloAction.</p> <p>(6) Hello.JSP <HTML: Errors> Tag Reads the ActionMessages object from the Request range, and read the ActionMessage object from the ActionMessages object, display the error message it contains on the web page. As shown in Figure 2-7.</p> <p>Figure 2-7 Logical verification failed Hello.JSP page</p> <p>2.8.4</p> <p>Logic verification process</p> <p>Next, enter the name "weiqin" in the HLLO.JSP HTML form, then click the [Submit] button. When the server responds to the customer request, the process is as follows.</p> <p>(1) Repeat</p> <p>2.8.3</p> <p>Steps 1 to 3 of the section.</p> <p>(2) HelloAction's Execute () method first performs logic verification, this time passes verification, then performs related business logic, finally calls an actionMApping.FindForward () method, parameter is "Sayello":</p> <p>// forward control to the specified surcess URI</p> <p>Return (Mapping.Findforward ("Sayhello");</p> <p>(3) Actionmapping.FindForward () method Looks from <action> element <forward> child elements, then returns to the corresponding ActionForward object, which represents the request forwarding path to "/Hello.jsp ".</p> <p>More specifically, ActionMapping looks for an ActionForward object that is "Sayhello" from the HashMap contained in itself. When the ActionServlet is initialized, the Struts configuration file is loaded, and the <forward> element can be stored in the ActionMapping object, and the <forward> element is stored in the <forward> element, and the configuration information storage of each <forward> sub-element is stored. In an ActionForward object, these ActionForward objects are stored in the HashMap of the ActionMapping object.</p> <p>(4) HelloAction's Execute () method then returns the ActionForward object to the ActionServlet, and the ActionServlet forwards the customer request to Hello.jsp.</p> <p>(5) Hello.JSP <bean: Message> Tags read text from Resource Bundle, output them onto the web, finally generate dynamic web pages, as shown in Figure 2-8. Figure 2-8 Hello.jsp page via data verification</p> <p>2.9 section</p> <p>This chapter demonstrates how to apply the Struts framework to the development of web applications by simple and complete HelloApp applications. Through this example, the reader can master the following:</p> <p>l Analyze application requirements, decompose application into models, views, and controllers to implement these needs.</p> <p>l Use the Struts tag library to create view components. The text content in the view component is saved in a dedicated message resource file, and accesses it through the Struts <bean: Message> tab in the JSP file, which can easily implement the internationalization of the Struts application, support multi-language.</p> <p>The L Struts framework passes the form data in the view to the controller component. The ActionForm bean is stored in the Request or Session range, which can be shared by the JSP component, the Struts tag, and the Action class.</p> <p>l Data verification is divided into two types: HTML form verification and business logic verification. The form is authenticated by the validate () method of an actionform bean. Business logic verification is implemented by an Action class or model component.</p> <p>l ActionMessage can represent a data validation error that is saved in the ActionMessages collection object. The ActionMessages object is saved within the Request range, and the Struts view component can access it via the <HTML: ERRORS> tag.</p> <p>l Action class Execute () method calls model components to complete business logic, and it can also decide which view component requesting the customer request forwarding to which view component.</p> <p>l The model component has the function of the package service to achieve detail. Developers can easily transplant the model components to the remote application server, which will not affect the other modules of the MVC.</p> <p>l The Java objects within the Request or Session range can be saved or accessed by calling the HTTPServletRequest or HttPSession's setAttribute (), and the GetAttribute () method, you can save the Java objects within the Request or Session range to implement interaction and sharing between view components and controller components.</p> <p>l Use the struts-config.xml file to configure the Struts application.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-97390.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="97390" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.042</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'q8G5o9AQR_2BCnXpMO3HBso5GyRwdGHVxvDv4S3bs_2BevponkRC4WvcG5Bju5FBuwY3jg_2FOBq_2FlRGPJwsv_2B'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>