Use Ajax to explain how Struts2 receives array forms.
Using the struts2 form to pass values, you can pass one or all attributes of an object, which is flexible and convenient. But if we need to pass an array and want struts to receive it correctly, what should we do?
The following describes how to use common forms and ajax. First, we have an entity, an action, and a jsp.
Student. java
public class Student{ private String name; private String num;}StudentAction.javapublic class StudentAction extends ActionSupport{ private List<Student> lstStu;}
Xy. jsp
<script type="text/javascript"> var stus = []; stus.push({num:"1",name:"xy1"}); stus.push({num:"2",name:"xy2"}); stus.push({num:"3",name:"xy3"});</script>
The following code is written in the script area of xy. jsp.
Common form-traverse the array and construct a form hidden field
var htmlContent = "";for(var i=0;i<stus.length;i++){ htmlContent += "<input type='hidden' name='lstStu[" + i + "].name' value='" + stus[i].name + " ' />"; htmlContent += "<input type='hidden' name='lstStu[" + i + "].num' value='" + stus[i].num + " ' />";}
Special Cases
<input type='hidden' name='lstStu.name' value='xy1' /><input type='hidden' name='lstStu.name' value='xy2' /><input type='hidden' name='lstStu.name' value='xy3' />
Struts can recognize the attributes of leaflets, indicating three different student. However, uploading two attributes won't work because struts doesn't know the combination. Not recommended.
Ajax form -- traverse the array and construct a json object
var param = {};for(var i=0;i<stus.length;i++){ param["lstStu[" + i + "].name"] = stus[i].name; param["lstStu[" + i + "].num"] = stus[i].num;}$.ajax({ data:param});
In fact, we have constructed such a json object.
data:{ lstStu[0].num:"1",lstStu[0].name:"xy1", lstStu[1].num:"2",lstStu[1].name:"xy2", lstStu[2].num:"3",lstStu[0].name:"xy3"}
Some people say that it is not convenient to directly upload the stus array as data to the Action? The answer is that it cannot be passed in this way, so that the action cannot receive or struts does not know how to process the sent array.
The content of this article is over and I hope it will help you.