Json distal pass objects (which contained json array), when the background of the Java, how when receiving SSM

JS code distal follows: 

var URL = "Web" ; 
var PostData = {
 "History" : [ 
                          {
                              "Time": "2017-10-18 10:10:10", // Time field: Time 
                            "option": " Human " // Option fields: user human, machine machine 
                           }, 
                          {
                             " Time ":" 2017-10-19 99:99:99 " ,
                             " Option ":" machine " 
                           } 
                         ],
                " OpenID ":" ABCDEFGHIJKLMN " ,  
                "type":"家庭"
              };
$.ajax({
type:"The POST" , 

URL: URL, 

// the JSON.stringify (), to convert the object into a string postdata 
Data: { "postdata": the JSON.stringify (postdata)}, // call ajax time, data such property must write. Must 
dataType: "JSON" , 
Success: function (Data) { 

} 
} 

}); 

the Java code is as follows 

// @RequestParam ( "PostData") is the key phrase, with the front end of the data: { "postdata": JSON.stringify (postdata)} corresponding to the attribute name to be consistent 

@RequestMapping ( "/ addQuestionIntelligence" )
 public @ResponseBody ResponseResult addQuestionIntelligence (@RequestParam ( "PostData") String PostData, the HttpServletRequest Request, the HttpSession the session) throws Exception { 

org.json.new org.json.JSONObject(postdata);

}

[Front-end to back-end transmission 

problems Background:
I want to submit personal information to SpringMVC number of passengers in a one-off form, the front-end HTML and SpringMVC Controller in how to deal with?

    The first method: the form is submitted to the array field receiver;
    second method: form submission to BeanListModel received;
    third method: the sequence of objects into Json Json string submitted to List received;
    fourth method: Json serialized string form object submitted to List received;
    fourth method is actually a third method of upgrading, is to turn into a form Json objects, then into Json submitted string;
    however, the fourth method is not support submit the form contains multiple-choice controls, so there should be an enhanced version of the fifth method.

The above four methods are common to both the User entity class code is as follows:

    public class User {
     
        Private ID Integer;
        Private String name;
        Private String pwd;
     
        @Override
        public String toString () {
            return "User {" +
                    "ID =" + + ID
                    ", name = '" + name +' \ '' +
                    ", Pwd = '" + + pwd' \ '' +
                    '}';
        }
        // ....... and there getter, setter methods omitted
     }

The first method: form submission to an array of field receiving
HTML code as follows:

    <form Action = "/ User / submitUserList_1" Method = "POST">
            ID: <INPUT type = "text" name = "ID"> a
            the Username: <INPUT type = "text" name = "name"> a
            Password: <INPUT type = "text" name = "pwd"> a a
     
            ID: <INPUT type = "text" name = "ID"> <br / >
            the Username: <INPUT type = "text" name = "name"> a
            Password:<input type="text" name="pwd"><br/><br/>
            <input type="submit" value="submit">
        </form>

Java代码如下:

    @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.中文"; }
            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;
        }

第2种方法:表单提交,以BeanListModel接收
HTML代码如下:

    <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代码:
In addition to just the public User class, but also a wrapper class of User UserModel:

    public class UserModel {
        Private List <User> Users;
     
        public List <User> the getUsers () {
            return Users;
        }
     
        public void setUsers (List <User> Users ) {
            this.users = Users;
        }
     
        public UserModel (List <the User> Users) {
            Super ();
            this.users = Users;
        }
     
        public UserModel () {
            Super ();
        }
     
    }

SPRINGMVC the 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.中文"; }
            result = this.showUserList(userList);
            return result;
        }

第3种方法:将Json对象序列化成Json字符串提交,以List接收
HTML代码:

    <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: "李四", pwd: "123"});
                customerArray.push({id: "2", name: "张三", pwd: "332"});
                $.ajax({
                    url: "/user/submitUserList_3",
                    type: "POST",
                    contentType : 'application/json;charset=utf-8', //设置请求头信息
                    dataType:"json",
                    //data: JSON.stringify(customerArray),// The Json Json target sequence into strings, JSON.stringify () method of the original ecological
                    data: $.toJSON(customerArray),            //将Json对象序列化成Json字符串,toJSON()需要引用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代码:

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

the fourth method: a serialized form object submitted Json string to List received
HTML code:

    <DOCTYPE HTML the PUBLIC "- // the W3C // the DTD HTML 4.01! // EN Transitional "
            " 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 = "the JavaScript" the src = "/ JS / jquery.min.js"> </ Script>
        <Script type = "text / JavaScript" Language = "the JavaScript">
            // sequence data into a form json format ( but not for the control of the form contains, for example check boxes, multiple selection SELECT)
            (function ($) {
                $ .fn.serializeJson = function () {
                    var jsonData1 = {};
                    var serializeArray this.serializeArray = ();
                    // first converted into { "id": [ "12 ", "14"], "name": [ "aaa", "bbb"], "pwd": [ "pwd1", "pwd2"]} this in the form of
                    $ (serializeArray) .each (function () {
                        IF (jsonData1 [the 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;
                        }
                    });
                    // 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式
                    var vCount = 0;                        var tmp = $ .isArray (jsonData1 [Item]) jsonData1 [Item] .length:?. 1;                    for (var Item in jsonData1) {
                    // array of internal calculations json maximum length


                        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', //设置请求头信息
                    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代码:

    @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.中文"; }
            result = this.showUserList(users);
            return result;
        }

总结:
1,2 ways to actually have a common BUG: If you submit when three records, some of the fields in front of the two records do not fill value, the reception in the SpringMVC not accurate. Furthermore, the two methods each need to add a name attribute in HMTL [index], if the span is marked with the words (such as the first set of standard controls is 0, the second subscript is the group 2), then in fact the SpringMVC 0-2 are three objects, that object is a default subscript 1 are all null values.
3 and 4 the most practical method.

Guess you like

Origin www.cnblogs.com/yangshuyuan1009/p/10984982.html