Struts dynamic form application

xiaoxiao2021-03-06  41

This article explains the reference of DYNAFORMS in Struts1.1 in an instance code ?? Translator's 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.ActionErrors; 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) {ActionErrors errors = new ActionErrors (); IF (NullBLANK (Lastname)) {Errors.Add ("LastName", New Actionerror ("Article1.lastname.Missing"));}}} (Nulloblank (Firstname)) {Errors.Add ("Firstname", New Actionerror (" Article1.firstname.Missing "));} {Errors.Add (" street ", new actionerror (" article1.street.missing ");}} f (nulloblank (city) {Errors. Add ("City", New Actionerror ("Article1.city.Missing"));}} (NullorBLANK (State)) {Errors.Add ("State", New Actionerror ("Article1.State.Missing");} IF (NULLORBLANK ("Postalcode", new actionerror ("article1.postalcode.missing));}} f (Nulloblank (Phone) {Errors.Add (" Phone ", New Actionerror (" Article1.phone.missing "));} Return Errors; Private String Firstname; Private String Street; Private Stri Ng city; private string postalcode; private string phone; privat

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 write method in the upper side (such a long code [Although most of the tools can automatically generate SET and GET methods] What is it? If you want to match a formbean for each form, then a 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> </ head> <h1> Example of a standard customer form </ h1> <html: form action = "/ addcustomer"> Last Name: <HTML: TEXT Property = "LastName" /> <html: errors proty = "lastname" /> <br> first name: <html: text property = "firstname" /> <html: errors proty = "firstname" /> <br> Street Addr: Text Property = "Street" /> <html: Errors Property = "Street" /> <br> city: <html: text proteTy = "city" /> <html: errors proty = "city" /> <br> State: <html: Text Property = "State" maxLENGTH = "2" size = "2" /> <html: errors proty = "state" /> <br> Postal code: <html: Text Property = "postalcode" maxlength = "5" size = "5" /> <html: errors proty = "postalcode" /> <br> TELEPHONE: <html: text property = "size =" 11 "size =" 11 "/> <html: errors proty =" phone "/> <br> <html: submit /> </ html: form> The corresponding action does not have a complex business code, just print from the value passed from the Client. Console.</p> <p>Article1.addcustomerction package article1;</p> <p>Import org.apache.struts.action.action; import org.apache.struts.action.actionmapping; import org.apache.struts.action.actionforward; import org.apache.struts.Action.ActionForm;</p> <p>Import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import javax.servlet.servletException; import java.ioException;</p> <p>public class AddCustomerAction extends Action {public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {CustomerForm custForm = (CustomerForm) form; System.out.println ( "lastName =" custForm.getLastName ( )); System.out.println ("firstname =" Custform.GetFirstName ()); System.out.Println ("street =" Custform.getStreet ()); System.out.Println ("City =" Custform.getCity (); system.out.println ("State =" Custform.getState ()); System.out.Println ("Postalcode =" Custform.getPostalcode (); System.Out.println (" Phone = " Custform.getphone ()); return mapping.findforward (" surcess ");}}</p> <p>Let's take a look at the configuration of Struts-Config.xml.</p> <p><struts-config> <form-beans> <form-bean name = "customerform" type = "jdj.Article1.customer" /> </ form-beans> <action-mapings> <action path = "/ addcustomer" TYPE = "article1.AddCustomerAction" name = "customerForm" scope = "request" input = "/ addCustomer.jsp"> <forward name = "success" path = "/ addCustomerSucceeded.jsp" redirect = "false" /> </ action > </ action-mappings> <message-resources parameter = "ApplicationResources" /> <plug-in classname = "org.apache.struts.validator.validatorPlugin"> <set-protety value = "/ web-inf / validator- Rules.xml "Property =" Pathnames "/> struts-config.xml </ plug-in> </ struts-config> <? XML Version =" 1.0 "encoding =" utf-8 "?> <! doctype struts- Config public "- // Apache Software Foundation // DTD Struts Configuration 1.1 // En" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> <form-beans > <form-bean name = "customerform" type = "article1.customerform" /> </ form-beans> <action-mapings> <action path = "/ addcustomer" type = "article1.addcustomerction" name = "Customerform" s Cope = "request" infut = "/ customer.jsp"> <forward name = "success" path = "/ addcustomersucceeded.jsp" redirect = "false" /> </ action> </ action-mapings> <message-resources Parameter = "ApplicationResources" /> <plug-in classname = "</p> <p>Org.apache.struts.validator.validatorPlugin "> <set-property value =" / web-inf / value "/> </ plug-in> </ struts-config> by </ plug-in> </ struts-config> Configure, Customerform to reference the Custemerform class, "/ addCustomer" Action uses Customerform and triggers article1.addcustomerction to process requests.</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" 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.adddynacustomaction package 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.io.IOException; 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 "));</p> <p>Return mapping.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.dynacustomerform 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) {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 "));} IF (nullorblank ((String) this.get (" Phone ")) {Errors.Add (" Phone ", new actionerror (" article1.phone.missing ");} return Errors;}} If so, we must change struts-config.xml to use Dynaac TIONFORM subclass, such an effect seems to return to the previous look (written for each table DYNAActionFORM), 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></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-56744.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="56744" 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.038</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 = 'XdqWcy1U_2BjvdJuwI0H8jRp6cHJMU6_2FuC_2BwoMwch7_2BO1c8uFEPbpXrEG_2B1NbS3NG7uXk45GscffC25PbS2scqBw_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>