Tag and create a radio button group by nested Struts

xiaoxiao2021-04-09  359

In this article, I will introduce the Nested Struts tag and Create a radio button group. Then I use a specific form bean to point to this tag and iterate the String [] array that saves the radio button value, assigns the same Name property to each value property.

See the download area to get a complete sample source code; if you need to download the Struts framework, see Resources.

Five steps

For the sake of simplicity, I use the same working example as the last in the dynamic check box to demonstrate the radio button. My simple user interface uses a radio button element to display the String [] array of Himalayas, the second SelectAin String array represents the selected select button. After creating a button, call a JavaScript function to preselect the radio button.

According to the example of Himalaya, the 诀窍 诀 窍 单 单 单 单 单 部分 部分 部分 部分 部分 部分 部分 部分:

A fake data class that accommodates Mountains and SelectAin data. A form bean, a string [] array and a specially selected button for the radio button. A JSP with a form showing the radio button in the desired state. A JSP, the elements selected in the form. A Action class, go from the form page to the display page.

The main difference between the radio button and the dynamic check box of the last school is: Struts does not provide a tool that automatically creates a Selected value, and this is usually required to create a dynamic radio button. Although the Checkbox and SELECT input types are quite simple in pre-selecting the function in the Struts JSP tag, the Radio Button input type requires different solutions. Fortunately, this requirement can be implemented using information from form beans and a few line JavaScript code, such as step 3.

Step 1. Create a data layer

I do a fake data class, and the data from the business layer is rendered to the application view layer, and the view layer is what I want to consider. The class named FakeData contains two static methods, such as Listing 1:

Listing 1. Fakedata.java

/ ** * Class Fakedata - Repesents the business logic * / public class fakedata {/ ** * Data for mountains * / public static final string [] mountains = {"everest", "kangchenjunga", "lhaotse" "," Makalu "," Cho Oyu "}; / ** * Data for Slected Mountain * / public static final string SELECTED_MOUNTAIN =" kangchenjunga ";

Creating a false data layer is a useful user interface development practice, because the continuous storage layer to be used for the final application is usually not seen for front-end developers. Therefore, it is not necessary to wait for the background team to complete the work, which can easily develop a fake data layer to simulate the API and functionality to be sent. Using a fake data layer, you can develop and reduce dependence on other teams. With a fake data layer, you can also define an API connection to other parts of the project and make sure there is less problem in integrating all parts.

Step 2. Create a form bean

The value that ultimately populates the application may come to a framework that is more complicated than the framework shown in Listing 1. For more beautiful examples, there is a good news that the form bean in Listing 2 does not have to do any heavy work, so it is just a simple JavaTM object with getter and setter methods. The actual value is inserted when the constructor is called. Listing 2. Radiotestform.java

package com.strutsrecipes; import org.apache.struts.action.ActionForm; / ** * Radio Button Test Form to show an array of radio buttons and * / public class RadioTestForm extends ActionForm {// -------- ---------------------- Fields --------------------------- --- / ** * The success selected mountain * / private string selectedmountain; / ** * The list of mountains for the radio button * / private string [] mountains; // ------------ --------------- Constructors ------------------------- / ** * Constructor - Using fakedata ... * / public radiotestform () {this.selectedMountain = fakedata.selected_mountain; this.mountains = fakedata.mountains;} // ------------------- - getter / setter methods --------------------- / ** * getter for the mountains * * @return the mountains array * / public string [] getMountains ( ) {return this.mountains;} / ** * setter for the mountains * * @Param m the mountains array * / public void setMountains (String [] m) {this.mountains = m;} / ** * Getter for selectedMountain * * @return the selected mountain * / public String getSelectedMountain () {return this.selectedMountain;} / ** * Setter For selectedMountain * * @Param sm the selectedmountain * / public void setselectedmountain (string sm) {this.selectedMountain = SM;}}

For the sake of clarity, I contain all Java code for the form bean. Note that Kangchenjunga is listed in the SelectAin and Mountains fields, and is instantiated in the constructor and fill it with the FakeData class. Now, I have enough information to pass Kangchenjunga to JSP, as the initial value of Preselected. Step 3. Create a radio button JSP

Listing 3 contains the JSP code of the form page, which contains the radio button and the pre-selected value in the form page. Note the relationship between Java files and logic, HTML, bean tags and JavaScript functions at the bottom of the form. I iterate on the Mountains collection to create a radio button. After this work is completed, I add JavaScript and fill the value of SelectedMountain, and compare the radio button array to select the correct button.

Listing 3. JSP containing radio buttons and preselected values

<% @ Taglib URI = "/ Tags / Struts-Bean" prefix = "bean"%> <% @ Taglib URI = "/ tags / struts-html" prefix = "html"%> <% @ Taglib URI = "/ Tags / struts-logic "prefix =" logic "%> <bean: message key =" testform.title "/> </ title> <html: base /> </ head> <body> <h3> <bean: message key = "testform.Heading" /> </ h3> <html: form action = "/ formaction" name = "Testform" Type = "com.strutsrecipe .Radiotestform "> <h4> <bean: Message key =" testform.instruction "/> </ h4> <! - Gets the successd radio button -> <bean: define id =" selectedradio "property =" selectedMountain " Name = "Testform" /> <! <logic: iped = "mountain" property = "mountains" name = "testform"> <% - you need this holppy to get the Value of the mountains to the page -%> <bean: define id = "mountainvalue"> <bean: Write name = "mountain" /> </ bean: define> <html: Radio PR Operty = "SELECTEDMOUNTAIN" value = "<% = mountainvalue%>" styleID = "<% = mountainValue%>" /> <bean: write name = "mountain" /> </ logic: Itereate> <br /> <</p> <p>HTML: Submit /> <html: reset /> <script type = "text / javascript"> <! - // Either of the following works. // uncomment the one you wish to try and comment the Other out. // var selectedRadio = document.getElementById ( "<bean: write // name =" selectedRadio "/>"); var selectedRadio = document.forms [ "testForm"] elements [ "<bean: write name =" selectedRadio "/>. "]; selectedradio.checked = true; -> </ script> </ html: form> </ body> </ html: html> Step 4. Create a display page</p> <p>The display page is basically the same as the page used in the check box, and the difference is just no iteration, because only one value is selected. It is only to list the Mountain in the bean, such as Listing 4:</p> <p>Listing 4. JSP displayed</p> <p><% @ Taglib Uri = "http://jakarta.apache.org/struts/tags-html" prefix = "html"%> <% @ Taglib URI = "http://jakarta.apache.org/struts/tags -bean "prefix =" bean "%> <% @ Taglib URI =" http://jakarta.apache.org/struts/tags-logic "prefix =" logic "%> <% - HTML Code, ETC .. -%> <bean: Write name = "mountain" /> <HR size = 5 color = "black" /> <% - some more html code, etc ... -%></p> <p>Step 5. Write an Action class</p> <p>Just as I mentioned in the previous article, the Action class did not work more than other components in this trick. It is only to get the value of the String array and SelectDmountain, and allow the display page to use them.</p> <p>Listing 5. Action class</p> <p>ipackage com.strutsrecipes; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; / ** * The Action for the Radio Button test * / public final class RadioTestAction EXTENDS ACTION {// ----------------------------------------- --------- / ** * The Action for the Radio Button test * / public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception {// Extract attributes needed String selectedMountains = ((Radiotestform) form) .getSelectedMountAin (); System.out.Println ("HTMLString Returned ********* / n" selectedMountAins); // Save your htmlstring in the session httpsession session = request.getations (); session.SetAttribute (constants.mountains); return (Mapping.Findforward ("Success");}}</p> <p>The truly role is JavaScript after the trick. First, I am in Listing 5, define a JSP script variable for the SelectMountain field in the JSP form, as shown below:</p> <p><bean: define id = "SELECTEDRADIO" proty = "selectedmountains" name = "testform" /></p> <p>In the form, I created a JavaScript function that contains two lines below:</p> <p>Var selradio = document.getElementByid ("<bean: write name =" SELECTEDIO "/>"); selradio.checked = true;</p> <p>In the client script, I created a Selradio JavaScript variable and finds all elements in the document (find), finds the element that matches the SELECTEDRADIO variable in the ID (or the styleid in the precompiled code). By setting the <html: Radio /> tag setting to the name / value of its name / value. When the JavaScript function is rapidly iterated between the ID of the page, the single radio button is set to Selected. alternative method</p> <p>The same effect can be produced with the JavaScript method as shown below:</p> <p>Var selectedradio = document.forms ["testform"]. Elements ["<bean: writename =" SELECTEDIO "/>" selectedradio.Checked = true;</p> <p>This script only distinguishes the Name property of the form element instead of the id attribute. Both implementations can work, so which specifically chooses which kind of personal needs and preferences. The actual output of the JSP form page looks like a list 6:</p> <p>Listing 6. Output of the JSP form page</p> <p><input type = "radio" name = "selectedMountain" value = "everest" id = "everest" /> everest <input type = "radio" name = "selectedmountain" value = "k2" id = "k2 "/> K2 <input type =" radio "name =" selectedMountain "value =" kangchenjunga "checked =" checked "id =" kangchenjunga "/> kangchenjunga <input type =" radio "Name = "SELECTEDMOUNTAIN" value = "lhaotse" id = "lhaotse" /> LHOTSE <input type = "radio" name = "selectedMountain" value = "makalu" ID = "MAKALU" /> MAKALU <Input Type = "Radio" name = "SelectedMountain" value = "cho oyu" id = "cho oyu" /> cho oyu</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-133179.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="133179" 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 = 'ulqEjaFrlXmfO8k4jkWw0zstjrh6kNZIqE5p2mYT2vBw6jXfi9a2yGj_2Bh0Oos0TZAFMMM3Ale3xyBShqnjhWzw_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>