We are too familiar with the form passing value in struts2. It is very easy to pass one or more values or attributes of an object.
But what should we do if we want to upload an array and want struts to receive it correctly?
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. java
Public 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 = 'den den 'name = 'lstu [" + I + "]. name 'value = '"+ stus [I]. name + "'/> ";
HtmlContent + = "<input type = 'den den 'name = 'lstu [" + I + "]. num 'value = '"+ stus [I]. num + "'/> ";
}
Special Cases
<Input type = 'did' name = 'lstu. name' value = 'xy1'/>
<Input type = 'did' name = 'lstu. name' value = 'xy2'/>
<Input type = 'did' name = 'lstu. 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"
} Www.2cto.com
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.