Using the Struts2 table conveys values, you can pass one or the individual attributes as an object, are very flexible and convenient. But what if we need to pass an array and expect struts to receive it correctly?
I'll explain it in two ways with plain form and Ajax. First we have the following 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>
Let's start with the following code written in the Xy.jsp script area.
Normal form--traversing an array, constructing a form-hidden field
var htmlcontent = "";
for (Var i=0;i<stus.length;i++) {
htmlcontent = "<input type= ' hidden ' name= ' lststu[" + i + "].name ' value= '" "+ st Us[i].name + "'/>";
Htmlcontent + = "<input type= ' hidden ' name= ' lststu[' + i +"].num ' value= ' "+ stus[i].num +" '/> ";
}
Special Circumstances
<input type= ' hidden ' name= ' lststu.name ' value= ' xy1 '/> <input ' the type= ' ' hidden ', ' name= ' Lststu.name '
Xy2 '/> <input type= hidden ' name= ' lststu.name ' value= ' Xy3 '
When the flyer attributes, struts can be recognized, representing 3 different student. But passing two attributes is not a good idea, because struts doesn't know the combination. Not recommended.
Ajax form-traversal arrays, constructing JSON objects
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 built 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 upload the Stus array as data to the action. The answer is not to pass so that the action cannot be received or that struts does not know what to do with the array.
The content of this article is over, I hope to help you.