Struts dynamic form application

zhaozj2021-02-16  86

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;</p> <p>Import org.apache.struts.Action.actionform;</p> <p>Import javax.servlet.http.httpservletRequest; 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" /></p> <p><plug-in classname = "org.apache.struts.validator.validatorPlugin"> <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 = bushfirstname = georgestreet = 1600 pennsylvania avenue nwcity = WashingtonState = DCPOSTALCODE = 20500Phone = 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 Function) Use DynaActionform, you can use the Form-Property XML tab, which allows you to define the properties of FormBean in struts-config.xml. In our example, Struts-Config.xml will look like this:</p> <p><form-bean name = "Dynacustomerform" type = "org.apache.struts.Action.DynaActionform"> <form-property name = "lastname" type = "java.lang.string" /> <form-property name = " Firstname "Type =" java.lang.string "/> <form-property type =" java.lang.string "name =" street "/> <form-protety name =" kind "type =" java.lang.string "/> <Form-protety name =" state "type =" java.lang.string "/> <form-property name =" postalcode "type =" java.lang.string "/> </ 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.adddynacustomactionpackage article1;</p> <p>Import org.apache.struts.action. *;</p> <p>Import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import javax.servlet.servletException; import java.ioException;</p> <p>public class AddDynaCustomerAction extends Action {public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {DynaActionForm custForm = (DynaActionForm) form; System.out.println ( "lastName =" custForm.get ( "lastname"); system.out.println ("firstname =" Custform.get ("firstname")); system.out.println ("street =" Custform.get ("street"); system. Out.println ("City =" Custform.get ("City")); System.out.Println ("State =" Custform.get ("State"); System.out.Println ("Postalcode =" Custform.get ("postalcode"); system.out.println ("Phone =" Custform.get ("Phone")); return maping.findforward ("Success");}}</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.dynacustomerformpackage articles;</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) {Return ((Str == Null) || (Str.Length () == 0);}</p> <p>public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) {ActionErrors errors = new ActionErrors (); if (nullOrBlank ((String) this.get ( "lastName"))) {errors.add ( "lastName", new ActionError ( "article1 .lastname.missing "));}} (NullorBlank ((String) this.get (" firstname ")) {Errors.Add (" firstname ", new actionerror (" article1.firstname.missing));} (NullorBlank ("street"))) {ErrorS.Add ("street", new actionerror ("article1.street.missing");}} (nullorblank ((String) this.get ( "City")) {Errors.Add ("City", new actionerror ("article1.city.missing"));}} (nullorblank ((string) this.get ("state")) {ErrorS.Add ("State", New Actionerror ("Article1.State.Missing")));}} (NullorBlank ((String) this.get ("Postalcode")) {Errors.Add ("Postalcode", New Actionerror ("Article1 .postalcode.missing "));}} (nullorblank ((string) this.get (" phone "))) {Errors.Add (" Phone " New Actionerror ("Article1.Phone.Missing"));} Return Errors;}} If this is the case, we must change Struts-config.xml to use the subclass of DynaActionform, which seems to be returned to the previous Sample (write DynaActionform for each table), huh, huh. . . So the recommended practice is to use the Validator Framework of Struts1.1, in this regard in the subsequent article</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-14617.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="14617" 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.037</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 = 'D_2F50udCO6RSLkUo3hCD7e7tXaD2zmxH8XLSzxPRNtV_2Bw0gYKa5r_2ByDK1YmFTD9nv6OFrAaf4dAbd7kumB6bujA_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>