A simple example shows the workflow of Struts

xiaoxiao2021-03-06  42

Our first Struts program will be a user registration program. Users will see a registration screen that contains 3 fields: user name, password, and password confirmation. Successful registration requires two passwords. If the registration is successful, the control will turn to a page, display the registration success Successful! .. If the input password is different twice, the control stream will turn to a page display failed.

This simple exercise will show the following:

l Create an HTML form;

l Get input from the HTML form;

l Handling input (business logic);

l Change the control flow based on dynamic input;

To accomplish this program, you need to build:

l an ActionForm

l an action

l struts-config.xml file

l three pages

that's it!

Create an ActionForm

ActionForm is a JavaBean extended org.apache.struts.Actionform class. This object captures the input by requesting. When the browser submits a form, it creates a parameter for the fields in each form in the request. ActionForm has a corresponding attribute for the fields in each HTML form. The ActionServlet matching the parameters in the request and the properties in the ActionForm. When the match is matched, the ActionServlet calls the setter method and enters the value in the request. In our exercise, the UserName field in the form requires a setUserName (String) method. The Password field requires SetPassword1 (String) and SetPassword2 (String) method. These methods are responsible for assembling instance variables hidden in RegisterForm JavaBean. The source code of RegisterForm is displayed in Listing 1.

Create registerAction

Action A Java class extends org.apache.struts.Action. ActionServlet is assembled, and then passes it to the action. Action is typically responsible for entering the check, access business information, and deciding which ActionForward returns to servlet.

Now, create a file, named registeraction.java, its content is the content of the code list 2:

Package app;

Import org.apache.struts.action. *;

Public class registerform eXtends actionform {

Protected string username;

Protected string password1;

Protected string password2;

Public string getUsername () {return this.username;

Public string getpassword1 () {return this.password1;};

Public string getpassword2 () {return this.password2;};

Public void setusername (string username) {this.username = usrname;

Public void setPassword1 (string password) {this.password1 = password;};

Public void setPassword2 (string password) {this.password2 = password;};

Code List 1.1 RegistrationForm

Create registerAction

Action A Java class extends org.apache.struts.Action. ActionServlet is assembled, and then passes it to the action. Action is typically responsible for entering the check, access business information, and deciding which ActionForward returns to servlet.

Now, create a file, named registeraction.java, its content is the code list 1.2:

Package app;

Import org.apache.struts.action. *;

Import javax.servlet.http. *;

Import java.io. *;

Public class registeraction extends action {

Public ActionForward Perform (ActionMapping Mapping,

Actionform Form,

HTTPSERVLETREQUEST REQ,

HttpservletResponse res) {

// 1cast the form to the registerform

Registerform rf = (registerform) form;

String username = rf.getusername ();

String password1 = rf.getpassword1 ();

String password2 = rf.getpassword2 ();

// 2appily business logic

IF (Password1.Equals (password2)) {

Try {

// 3 Return ActionForward for Success

UserDirectory.getInstance (). Setuser (username, password1);

Return mapping.findforward ("Success");

} catch (userdirectoryexception e) {

Return mapping.findforward ("failure");

}

}

// 4 Return ActionForward for Failure

Return mapping.findforward ("failure");

}

}

Code List 1.2 Registeraction.java

Although it is very simple, our registerAction has been a typical thing for Action. At 1, the input ActionForm is converted to RegisterForm. We can get the contents of UserName, Password1, and Password2. If the password matches two times, we add the user to the userDirectory 3 and return to the ActionForward corresponding to the Success. UserDirectory is a Helper class that records usernames and passwords to a standard properties file. Otherwise, return an actionforward corresponding to Failure.

When we create a struts-config file next step, we will identify an ActionForward object representative of Success and Failure.

Create a struts configuration file (struts-config.xml)

The struts-config.xml file contains the ActionServlet to process more information on the application request. To practice, we create an empty Struts-Config.xml file. What you need to do is to fill in some details. The file is stored in the / WebApps / Register / Web-INF / directory, you need to change:

First, add / register to the Path property of element. ActionServlet uses a web container forward to its URI to select the correct Action class. URI and ActionMApping Path properties match. Here, the path requested must match the prefix and the suffix and / register. Prefix or suffix is ​​usually / do / or .do. In our exercise, set the suffix to .do. When the URI has a .do extension, the container knows to forward the request to the ActionServlet. Struts will automatically remove the extension, so we don't have to add them when configured.

Next step

Registerform

Name attribute to element. Element Use the Name property to identify which ActionForm will be created and assemble the submitted form to him.

Then, add

App.Registerction

The type attribute of the element. The ActionServlet uses this property to identify the Action class that will be used to process the request.

Next, under the element, add

Success

Go to the Name property, and

/success.html

Go to the Path property. Finally, add it in another

Failure

To the Name property,

/FAILURE.HTML

Go to the Path property.

These elements will create an ActionForward object, we will use it to select the program's control flow. The element defines the association between the logical name used in the RegisterAction.

Struts-config.xml Source code See Code 3.

"- // Apache Software Foundation // DTD Struts Configuration 1.0 // En"

"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

Type = "app.register"

Name = "registerform">

Code list 1.3 struts-config.xml

The STRUTS framework treats the struts-config.xml file as deployment descriptor. It allows us to create and change the association of actionmapping and paths without recompiling Java classes. We can also change the connection between the page without changing the JSP template.

Create a page

The final step is to create success.html, failure.html, and register.jsp page.

The source code of 3 files is as follows, see the code list 1. 4, 1. 5, 1.6. Store in the / WebApps / register directory.

Success </ Title></p> <p></ HEAD></p> <p><Body></p> <p>Registration succeeded!</p> <p><P> <a href="register.jsp"> Try Another? </a> </ p></p> <p></ Body></p> <p></ Html></p> <p>Code List 1.4 Success HTML</p> <p><Html></p> <p><HEAD></p> <p><Title> Failure </ Title></p> <p></ HEAD></p> <p><Body></p> <p>Registration failed!</p> <p><P> <a href="register.jsp"> try again? </a> </ p></p> <p></ Body></p> <p></ Html></p> <p>Code list 1.5 Failure.html</p> <p><% @ Taglib URI = "/ Web-INF / STRUTS-FORM.TLD" prefix = "form"%></p> <p><form: form action = "register.do"></p> <p>Username: <form: text proteth = "username" /> <br></p> <p>ENTER Password: <form: Password Property = "Password1" /> <br></p> <p>RE-ENTER Password: <form: Password property = "password2" /> <br></p> <p><form: submit value = "register" /></p> <p></ form: form></p> <p>Code list 1.6 register.jsp</p> <p>At this time, all work to build a simple Struts application is done.</p> <p>How do it work?</p> <p>When you know the browser to the address http: // localhost: 8080 / register / register.jsp, Tomcat is machined in the usual situation. Enter username and password, click on the Register submission page. The browser is in the request of the POST form. Which registered path will be sent to the container check. Then request forward to the ActionServlet and processed by registerAction. The validity of the registerAction check the input before returning to success or failure. The last servlet forwards the control to the response page based on the returned ActionForWard.</p> <p>Look at the register.jsp in the code 1.6, you can see that the form is submitted to the URI / Register. But if you observe the pages submitted, it will be found to be submitted to register.do. The struts form tag is automatically plus the .do prefix. When we set up a program skeleton, we asked all requests for matching * .do to be passed to the ActionServlet. When receiving a request, the first thing ActionServlet is to find an actionMApping to match the request to the request. ActionMapping is a JavaBean created according to Struts-Config.xml file. We give XML specific files, but when runtime, Struts references is object instead of an XML document.</p> <p>From the code 1.3, we can use this element to create a mapping to the Path / Register:</p> <p><action</p> <p>PATH = "/ register"</p> <p>Type = "app.register"</p> <p>Name = "registerform"</p> <p>INPUT = "/ register.jsp"></p> <p>Then, the ActionServlet checks if there is Name property and this mapping:</p> <p><action</p> <p>PATH = "/ register"</p> <p>Type = "app.register"</p> <p>Name = "registerform"</p> <p>INPUT = "/ register.jsp"></p> <p>Here / Register mapping identifies a Form Bean through the name of RegisterForm. ActionServlet uses this</p> <p>A name property to find the corresponding ActionFormBean object. The type (TYPE) identified by the from bean is used to create an actionform object:</p> <p><form-beneans></p> <p><Form-bean</p> <p>Name = "registerform"</p> <p>TYPE = "registerform" /></p> <p></ form-beans></p> <p><action-mappings></p> <p><action</p> <p>PATH = "/ register"</p> <p>Type = "app.register"</p> <p>Name = "registerform"</p> <p>INPUT = "/ register.jsp"></p> <p><forward</p> <p>Name = "success"</p> <p>PATH = "/ success.html" /></p> <p><forward</p> <p>Name = "failure"</p> <p>Path = "/ failure.html" /></p> <p></ action></p> <p></ action-mappings></p> <p>Here, servlet will use the RegisterForm class:</p> <p><form-beneans></p> <p><Form-bean</p> <p>Name = "registerform"</p> <p>TYPE = "app.registerform" /></p> <p></ form-beans></p> <p>Once RegisterForm is instantiated, the ActionServlet is attempting to call the RegisterForm's setter method for the input domain in the request. In the example, they are setUsername, setpassword1, and setpassword2. This parameter will be ignored if a setter method does not exist. The TYPE attribute of the ActionMapping object is an ActionServlet to instantiate the class name of the ActionForm. Here, you will use the RegisterAction object you created. The Perform method of the RegisterAction object is called and passed a reference to the registerform that is created and assembled in front:</p> <p><action</p> <p>PATH = "/ register"</p> <p>Type = "app.register"</p> <p>Name = "registerform"</p> <p>INPUT = "/ register.jsp"></p> <p><forward</p> <p>Name = "success"</p> <p>PATH = "/ success.html" /></p> <p><forward</p> <p>Name = "failure"</p> <p>Path = "/ failure.html" /></p> <p></ action></p> <p>Depending on the execution result of the Perform method, one of the two ActionForward will be returned. The FindForward () method uses a string parameter to find the Forward object that matches the Name property. The Path property is used by the ActionServlet to decide which page to complete the response:</p> <p><forward</p> <p>Name = "success"</p> <p>PATH = "/ success.html" /></p> <p><forward</p> <p>Name = "failure"</p> <p>Path = "/ failure.html" /></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-53761.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="53761" 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.044</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 = 'N4QwMXkKd080YF64bcd_2Fe_2FL5g_2ByDVzl0duYPW2_2FoUYMibYuEvH903CuCoxpz5BYoTcTK8mcmN9O1p4Ww'; 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>