SpringMVC four ways to receive multiple objects

  • 2020-06-01 09:50:25
  • OfStack

Background:

I need to submit the personal information of multiple passengers to SpringMVC, HTML and SpringMVC Controller at the same time once in one form. What should I do?

The first method: form submission, received as an array of fields;
The second method: form submission, received in BeanListModel;
The third method: serialize the Json object into an Json string and submit it to receive it as List;
The fourth method: serialize the form object into an Json string and submit it to receive it as List;
The fourth method is actually an upgrade of the third method, which turns the form into an Json object and then into an Json string for submission.

However, the fourth method does not yet support submission of forms with multiple select controls, so there should be a fifth enhanced method.

All the above four methods share the same User entity class. The code is as follows:


public class User {

 private Integer id;
 private String name;
 private String pwd;

 @Override
 public String toString() {
 return "User{" +
  "id=" + id +
  ", name='" + name + '\'' +
  ", pwd='" + pwd + '\'' +
  '}';
 }
 // ....... There is something getter , setter Method, omitted 
 }

The first method: form submission, received as an array of fields

The HTML code is as follows:


 <form action="/user/submitUserList_1" method="post">
 ID:<input type="text" name="id"><br/>
 Username:<input type="text" name="name"><br/>
 Password:<input type="text" name="pwd"><br/><br/>

 ID:<input type="text" name="id"><br/>
 Username:<input type="text" name="name"><br/>
 Password:<input type="text" name="pwd"><br/><br/>
 <input type="submit" value="submit">
 </form>

The Java code is as follows:


 @RequestMapping(value = "/submitUserList_1", method ={RequestMethod.POST})
 @ResponseBody
 public String submitUserList_1(HttpServletResponse response,Integer[] id, String[] name, String[] pwd)
    throws Exception{
 String result = "";
 if(id == null || id.length <= 0){ return "No any ID. Chinese "; }
 List<User> userList = new ArrayList<User>();
 for (int i = 0; i < id.length; i++ ) {
  User user = new User();
  user.setId(id[i]);
  user.setName(name[i]);
  user.setPwd(pwd[i]);
  userList.add(user);
 }
 result = this.showUserList(userList);
 return result;
 }

The second method: form submission, received as BeanListModel

The HTML code is as follows:


 <form action="/user/submitUserList_2" method="post">
 ID:<input type="text" name="users[0].id"><br/>
 Username:<input type="text" name="users[0].name"><br/>
 Password:<input type="text" name="users[0].pwd"><br/><br/>

 ID:<input type="text" name="users[2].id"><br/>
 Username:<input type="text" name="users[2].name"><br/>
 Password:<input type="text" name="users[2].pwd"><br/><br/>
 <input type="submit" value="Submit">
 </form>

Java code:
In addition to the User class that you just Shared, you need to encapsulate a container class UserModel for User:


public class UserModel {
 private List<User> users;

 public List<User> getUsers() {
 return users;
 }

 public void setUsers(List<User> users) {
 this.users = users;
 }

 public UserModel(List<User> users) {
 super();
 this.users = users;
 }

 public UserModel() {
 super();
 }

}

SpringMVC Controller method:


 @RequestMapping(value = "/submitUserList_2", method ={RequestMethod.POST})
 @ResponseBody
 public String submitUserList_2(UserModel users)
  throws Exception{
 String result = "";
 List<User> userList = users.getUsers();
 if(userList == null || userList.size() <= 0){ return "No any ID. Chinese "; }
 result = this.showUserList(userList);
 return result;
 }

The third method: serialize the Json object into an Json string and submit it to be received by List

HTML code:


<head>
 <title>submitUserList_3</title>
 <meta http-equiv="content-type" content="text/html; charset=utf-8">
 <script language="JavaScript" src="/js/jquery.min.js" ></script>
 <script language="JavaScript" src="/js/jquery.json.min.js" ></script>
 <script type="text/javascript" language="JavaScript">
 function submitUserList_3() {alert("ok");
  var customerArray = new Array();
  customerArray.push({id: "1", name: " li 4", pwd: "123"});
  customerArray.push({id: "2", name: " zhang 3", pwd: "332"});
  $.ajax({
  url: "/user/submitUserList_3",
  type: "POST",
  contentType : 'application/json;charset=utf-8', // Sets the request header information 
  dataType:"json",
  //data: JSON.stringify(customerArray), // will Json Object serialization into Json String, JSON.stringify() Protoecological method 
  data: $.toJSON(customerArray),  // will Json Object serialization into Json String, toJSON() Need to quote jquery.json.min.js
  success: function(data){
   alert(data);
  },
  error: function(res){
   alert(res.responseText);
  }
  });
 }
 </script>
</head>

<body>
 <h1>submitUserList_3</h1>
 <input id="submit" type="button" value="Submit" onclick="submitUserList_3();">
</body>

Java code:


 @RequestMapping(value = "/submitUserList_3", method ={RequestMethod.POST})
 @ResponseBody
 public String submitUserList_3(@RequestBody List<User> users)
  throws Exception{
 String result = "";
 if(users == null || users.size() <= 0){ return "No any ID. Chinese "; }
 result = this.showUserList(users);
 return result;
 }

Method 4: serialize the form object into an Json string and submit it to receive it as List

HTML code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <title>submitUserList_4</title>
 <meta http-equiv="content-type" content="text/html; charset=utf-8">
 <script language="JavaScript" src="/js/jquery.min.js" ></script>
 <script type="text/javascript" language="JavaScript">
 // Serialize the form into json Formatted data ( This does not apply to forms that contain controls, such as checkboxes and multiple selections select)
 (function($){
  $.fn.serializeJson = function(){
  var jsonData1 = {};
  var serializeArray = this.serializeArray();
  //  First converted into a {"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]} This form 
  $(serializeArray).each(function () {
   if (jsonData1[this.name]) {
   if ($.isArray(jsonData1[this.name])) {
    jsonData1[this.name].push(this.value);
   } else {
    jsonData1[this.name] = [jsonData1[this.name], this.value];
   }
   } else {
   jsonData1[this.name] = this.value;
   }
  });
  //  Again into [{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}] In the form of 
  var vCount = 0;
  //  To calculate json Internal array maximum length 
  for(var item in jsonData1){
   var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
   vCount = (tmp > vCount) ? tmp : vCount;
  }

  if(vCount > 1) {
   var jsonData2 = new Array();
   for(var i = 0; i < vCount; i++){
   var jsonObj = {};
   for(var item in jsonData1) {
    jsonObj[item] = jsonData1[item][i];
   }
   jsonData2.push(jsonObj);
   }
   return JSON.stringify(jsonData2);
  }else{
   return "[" + JSON.stringify(jsonData1) + "]";
  }
  };
 })(jQuery);

 function submitUserList_4() {alert("ok");
  var jsonStr = $("#form1").serializeJson();
  //console.log("jsonStr:\r\n" + jsonStr);
  //alert(jsonStr);
  $.ajax({
  url: "/user/submitUserList_4",
  type: "POST",
  contentType : 'application/json;charset=utf-8', // Sets the request header information 
  dataType:"json",
  data: jsonStr,
  success: function(data){
   alert(data);
  },
  error: function(res){
   alert(res.responseText);
  }
  });
 }
 </script>
</head>

<body>
 <h1>submitUserList_4</h1>
 <form id="form1">
 ID:<input type="text" name="id"><br/>
 Username:<input type="text" name="name"><br/>
 Password:<input type="text" name="pwd"><br/><br/>

 ID:<input type="text" name="id"><br/>
 Username:<input type="text" name="name"><br/>
 Password:<input type="text" name="pwd"><br/><br/>
 <input type="button" value="submit" onclick="submitUserList_4();">
 </form>
</body>
</html>

Java code:


@RequestMapping(value = "/submitUserList_4", method ={RequestMethod.POST})
@ResponseBody
public String submitUserList_4(@RequestBody List<User> users)
  throws Exception{
 String result = "";
 if(users == null || users.size() <= 0){ return "No any ID. Chinese "; }
 result = this.showUserList(users);
 return result;
 }

Conclusion:

The first and second methods actually have a common BUG: if three records are submitted and some fields of the previous two records are not filled in, it is not received correctly in SpringMVC. Moreover, every 2 methods in HMTL need to add [subscript] to the name property. If the subscript has a span (for example, the subscript of group 1 is 0, and the subscript of group 2 is 2), then SpringMVC actually contains between 0 and 23 objects. The object whose subscript is 1 by default is all null.

The third and fourth methods are the most practical.


Related articles: