Struts dynamic form application

zhaozj2021-02-12  158

Struts dynamic form application

Original connection: http://www.developer.com/java/web/Article.php/2214681

By James M. Turner

This article explains the reference of DynaForms in Struts1.1 in instance code - Translator Note

If you have used Struts Previous versions, you will notice that you need to spend a lot of time to write an actionform class file, and these types of files are very critical for Struts (it acts as part of "View"), usually it The structure is Bean Properties plus a validate method (sometimes reset method).

With the launch of the Struts1.1, the developer has another way to complete the previous tasks: use Dynabeans. Dynabeans dynamically generate Java Beans. This means that we can configure (usually using XML)

To generate FormBean instead of hard coding in FormBean.

To learn how Dynabeans (Struts is DynaForms), let's take a simple form, the fields are: Name, Address, Telephone, etc., the following code is the usual way of writing (not using DynaForms).

Article1.customerform

Package article1;

Import org.apache.struts.Action.actionform;

Import org.apache.struts.Action.Actionerro;

Import org.apache.struts.action.actionmapping;

Import org.apache.struts.Action.Actionerror;

Import javax.servlet.http.httpservletRequest;

Public class customerform extends actionform {

Protected Boolean NullorBlank (String Str) {

Return ((Str == Null) || (str.length () == 0));

}

Public ActionerRors Validate (ActionMapping Mapping,

HttpservletRequest request) {

ActionerroS Errors = new actionerrors ();

IF (NullorBlank (Lastname)) {

Errors.Add ("lastname",

New Actionerror ("Article1.lastname.Missing")));

}

IF (nullorblank (firstname)) {

Errors.Add ("firstname",

New ActionError ("Article1.Firstname.Missing")));

}

IF (Nulloblank (Street) {

Errors.Add ("street",

New ActionError ("Article1.street.Missing");

}

IF (nullorblank (city) {

Errors.Add ("City",

New Actionerror ("Article1.city.Missing"));

}

IF (nullorblank (state)) {

Errors.Add ("State", New Actionerror ("Article1.State.Missing")));

}

IF (NullorBlank (Postalcode)) {

Errors.Add ("Postalcode",

New ActionError ("Article1.Postalcode.Missing"));

}

IF (NullorBlank (Phone)) {

Errors.Add ("Phone",

New ActionError ("Article1.Phone.Missing"));

}

Return Errors;

}

PRIVATE STRING LASTNAME;

Private string dimstname;

PRIVATE STRING STREET;

PRIVATE STRING CITY;

PRIVATE STRING State;

PRIVATE STRING POSTALCODE;

PRIVATE STRING

Public string getlastname () {

Return Lastname;

}

Public void setlastname (String lastname) {

THIS.LASTNAME = LastName;

}

Public string getFirstName () {

Return firstname;

}

Public void setfirstname (String firstname) {

THIS.FIRSTNAME = firstName;

}

Public string getStreet () {

Return street;

}

Public void setstreet (String Street) {

THIS.STREET = STREET;

}

Public string getcity () {

Return city;

}

Public void setcity (string city) {

THIS.CITY = CITY;

}

Public string getState () {

Return State;

}

Public void setState (string state) {

THIS.STATE = State;

}

Public string getpostalcode () {

Return Postalcode;

}

Public void setPostalcode (String Postalcode) {

THIS.POSTALCODE = Postalcode;

}

Public String getphone () {

Return Phone;

}

Public void setphone (string phone) {

This.Phone = Phone;

}

}

Seeing the next way (such a long code [Although most of the tools can automatically generate set and get methods]? If you want to match a FORMBEAN for each form, you will be a more painful thing - - Translator's Note), you know that it is a standard JavaBean, just a validate method, the Validate method ensures that the Client break is legal.

The corresponding JSP page is also very simple, as follows:

Customer.jsp

<% @ Taglib Uri = "/ Web-INF / C.TLD" prefix = "c"%>

<% @ taglib prefix = "FMT" URI = "/ Web-INF / FMT.TLD"%> <% @ Taglib URI = "/ Web-INF / STRUTS-TILES.TLD" prefix = "tiles"%>

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

Example of A Standard Customer Form </ Title></p> <p></ hEAD></p> <p><H1> Example of A Standard Customer Form </ h1></p> <p><html: form action = "/ addcustomer"></p> <p>Last Name: <html: text property = "lastname" /></p> <p><html: Errors Property = "Lastname" /> <br></p> <p>First Name: <html: text property = "firstname" /></p> <p><HTML: Errors Property = "firstname" /> <br></p> <p>Street Addr: <HTML: Text Property = "Street" /></p> <p><html: Errors Property = "Street" /> <br></p> <p>City: <html: Text property = "city" /></p> <p><html: Errors Property = "City" /> <br></p> <p>State: <html: text property = "state" maxlength = "2" size = "2" /></p> <p><html: Errors Property = "State" /> <br></p> <p>Postal code: <html: text property = "postalcode" maxlength = "5"</p> <p>SIZE = "5" /></p> <p><html: Errors Property = "Postalcode" /> <br></p> <p>Telephone: <html: text property = "phone" maxlength = "11" size = "11" /></p> <p><html: Errors Property = "Phone" /> <br></p> <p><html: submit /></p> <p></ html: form></p> <p>The corresponding action does not have a complex service code, just prints the values ​​passed from the Client end to the console.</p> <p>Article1.addcustomerction</p> <p>Package article1;</p> <p>Import org.apache.struts.Action.action;</p> <p>Import org.apache.struts.action.actionmapping;</p> <p>Import org.apache.struts.action.actionforward; import org.apache.struts.action.Actionform;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import javax.servlet.servletException;</p> <p>Import java.io.ioException;</p> <p>Public class addcustomerction extends action {</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>Httpservletresponse response</p> <p>Throws servletexception, ioException {</p> <p>Customerform Custform = (CUSTOMERFORM) Form;</p> <p>System.out.println ("Lastname ="</p> <p> Custform.getLastName ());</p> <p>System.out.println ("firstname ="</p> <p> Custform.GetFirstName ());</p> <p>System.out.println ("street =" Custform.getStreet ());</p> <p>System.out.println ("City =" Custform.getCity ());</p> <p>System.out.println ("State =" Custform.getState ());</p> <p>System.out.println ("Postalcode ="</p> <p> Custform.getPostalcode ());</p> <p>System.out.println ("Phone =" Custform.getphone ());</p> <p>Return mapping.findforward ("Success");</p> <p>}</p> <p>}</p> <p>Let's take a look at the configuration of Struts-Config.xml.</p> <p><struts-config></p> <p><form-beneans></p> <p><form-bean name = "Customerform" type = "jdj.Article1.customer" /></p> <p></ form-beans></p> <p><action-mappings></p> <p><action path = "/ addcustomed" type = "article1.addcustomerction"</p> <p>Name = "Customerform" Scope = "Request"</p> <p>INPUT = "/ addcustom.jsp"></p> <p><forward name = "success" path = "/ addcustomersucceeded.jsp"</p> <p>REDIRECT = "false" /></p> <p></ action></p> <p></ action-mappings></p> <p><message-resources parameter = "ApplicationResources" /> <plug-in classname = "org.apache.struts.validator.validatorPlugin"></p> <p><set-protety value = "/ web-inf / validator-rules.xml"</p> <p>Property = "pathnames" /></p> <p>Struts-config.xml </ plug-in> </ struts-config></p> <p><? XML Version = "1.0" encoding = "UTF-8"?></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><struts-config></p> <p><form-beneans></p> <p><form-bean name = "customerform" type = "article1.customerform" /></p> <p></ form-beans></p> <p><action-mappings></p> <p><action path = "/ addcustomed" type = "article1.addcustomerction"</p> <p>Name = "Customerform" Scope = "Request" Input = "/ Customer.JSP"></p> <p><forward name = "success" path = "/ addcustomersucceeded.jsp"</p> <p>REDIRECT = "false" /></p> <p></ action></p> <p></ action-mappings></p> <p><message-resources parameter = "ApplicationResources" /></p> <p><plug-in classname = "org.apache.struts.validator.validatorPlugin"></p> <p><set-protety value = "/ web-inf / validator-rules.xml"</p> <p>Property = "pathnames" /></p> <p></ plug-in></p> <p></ Struts-Config></p> <p>By configuring, Customerform, "/ AddCustomer" Action uses CUSTEMERFORM, and triggered Article1.AddCustomraction to process requests.</p> <p>The following figure adds a Customer empty list picture</p> <p>If nothing is filled, the following figures will appear feedback information:</p> <p>If you have legal all your information, you can see the following information on the console:</p> <p>Lastname = Bush</p> <p>Firstname = george</p> <p>Street = 1600 Pennsylvania Avenue NW</p> <p>City = WashingtonState = DC</p> <p>Postalcode = 20500</p> <p>Phone = 2024561414</p> <p>Up to now, the upper code is familiar with Struts. It should be very familiar. If the new features of Struts1.1 are applied, you will use fewer code to complete the same functions described above. Using DynaForms, we should change the information of Customerform in Struts-Config.xml to use org.apache.struts.Action.DynaActionform (for easy readers to use the difference before and after use, we will use new types of JSP pages to complete the same Features)</p> <p>With DynaActionForm, you can use the Form-Property XML tab, which allows you to define the property elements of the FormBean in struts-config.xml. In our example, Struts-Config.xml will look like this:</p> <p><form-bean name = "Dynacustomerform"</p> <p>Type = "org.apache.struts.action.dynaactionform"></p> <p><form-protety name = "lastname" type = "java.lang.string" /></p> <p><form-property name = "firstname" type = "java.lang.string" /></p> <p><form-protety type = "java.lang.string" name = "street" /></p> <p><form-protety name = "city" type = "java.lang.string" /></p> <p><form-property name = "state" type = "java.lang.string" /></p> <p><form-protety name = "postalcode" type = "java.lang.string" /></p> <p></ form-bean></p> <p>The above changes have no impact on the JSP page. However, you have to make a slight change for the original Action should be: You are now not transferring FORMBEAN (no get set method) in Execute (), so you should transform the Form to DynaActionform, then use method get (filename) to get The new Action code of the Client end data is as follows:</p> <p>Article1.adddynacustomaction</p> <p>Package article1;</p> <p>Import org.apache.struts.action. *;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import javax.servlet.servletException;</p> <p>Import java.io.ioException;</p> <p>Public class adddynacustomaction extends action {</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>HttpservletResponse response) throws servletexception, ioException {</p> <p>DynaActionform Custform = (DynaActionform) Form;</p> <p>System.out.println ("LastName =" Custform.get ("Lastname"));</p> <p>System.out.println ("firstname =" Custform.get ("firstname");</p> <p>System.out.println ("Street =" Custform.get ("street");</p> <p>System.out.println ("City =" Custform.get ("city"));</p> <p>System.out.println ("State =" Custform.Get ("State"));</p> <p>System.out.println ("Postalcode ="</p> <p> Custform.Get ("Postalcode"));</p> <p>System.out.println ("Phone =" Custform.get ("Phone"));</p> <p>Return mapping.findforward ("Success");</p> <p>}</p> <p>}</p> <p>As can be seen from the code, it seems that "shield" Actionform, but we are also "lost" some other things, such as: strict input of legitimacy. There are two ways to recover the calibration function: First, create a subclass of DynaActionForm, then implement the validate () method in the subclass. As follows:</p> <p>Article1.dynacustomerform</p> <p>Package article1;</p> <p>Import org.apache.struts.action. *;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Public class Dynacustomerform Extends DynaActionform {</p> <p>Protected Boolean NullorBlank (String Str) {</p> <p>Return ((Str == Null) || (str.length () == 0));</p> <p>}</p> <p>Public ActionerRors Validate (ActionMapping Mapping,</p> <p>HttpservletRequest request) {</p> <p>ActionerroS Errors = new actionerrors ();</p> <p>IF (NullorBlank (String) this.get ("Lastname"))) {</p> <p>Errors.Add ("lastname",</p> <p>New Actionerror ("Article1.lastname.Missing")));</p> <p>}</p> <p>IF (nullorblank ((string) this.get ("firstname"))) {</p> <p>Errors.Add ("firstname",</p> <p>New ActionError ("Article1.Firstname.Missing")));</p> <p>}</p> <p>IF (NullorBlank ((String) this.get ("street"))) {</p> <p>Errors.Add ("street",</p> <p>New ActionError ("Article1.street.Missing");</p> <p>}</p> <p>IF (NullorBlank (String) this.get ("city"))) {</p> <p>Errors.Add ("City", New Actionerror ("Article1.city.Missing");</p> <p>}</p> <p>IF (nullorblank (String) this.get ("state"))) {</p> <p>Errors.Add ("State",</p> <p>New Actionerror ("Article1.State.Missing");</p> <p>}</p> <p>IF (NullorBlank ((String) this.get ("postalcode"))) {</p> <p>Errors.Add ("Postalcode",</p> <p>New ActionError ("Article1.Postalcode.Missing"));</p> <p>}</p> <p>IF (NullorBlank ((String) this.get ("Phone"))) {</p> <p>Errors.Add ("Phone", New Actionerror ("Article1.Phone.Missing"));</p> <p>}</p> <p>Return Errors;</p> <p>}</p> <p>}</p> <p>If so, we must change struts-config.xml to use the subclass of DynaActionform, such an effect seems to return to the previous look (write DynaActionform for each table), huh, huh. . .</p> <p>So the recommended practice is to use the Validator Framework for Struts1.1, in this regard, in the subsequent article.</p> <p>About the Author:</p> <p>James Turner is the owner and manager of Black Bear Software, LLC, which specializes in custom Java-based e-Commerce and CRM solutions delivery He is also the author of "MySQL and JSP Web Applications:. Data-Driven Programming Using Tomcat and MySQL (ISBN: 0672323095) AND is The Co-Author of "Struts: Kick Start" (ISBN: 0672324725), Which Will Be Published in November@blackbear.com.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-6100.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="6100" 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.045</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 = '8HyqyHS1RxhGgdW4_2FiUeIxUY80tZfKm9raimFN9bprxzO1G_2FrwNW6Na4l58i9rxxOEv_2FHFEjfv_2F4miwn2ENJkg_3D_3D'; 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>