springmvc-Processing of Ajax (with JSON type) (2)

Source: Internet
Author: User

A generic type converter is written here: Used to convert a shape such as: Firstname=jack&lastname=lily&gender=1&foods=steak&foods=pizza&quote =enter+your+favorite+quote!&education=jr.high&tofd=day to Student object. /** * @author Solverpeng * @create 2016-08-22-17:37 */public final class Injectutil<t> {private static final Log    Ger LOGGER = Loggerfactory.getlogger (Injectutil.class);        public static <T> T Converter2obj (String source, class<t> tclass) {T t = null;            try {t = tclass.newinstance ();            map<string, object> params = new hashmap<string, object> ();                if (Source = null && source.length () > 0) {string[] fields = Source.split ("&");                    for (String field:fields) {string[] Fieldkeyvalue = Field.split ("\\=");                    String fieldkey = fieldkeyvalue[0];                    String fieldvalue = fieldkeyvalue[1];    if (Params.containskey (Fieldkey)) {                    Object keyvalueretrieved = Params.get (Fieldkey); if (keyvalueretrieved instanceof String) {arraylist<string> values = new ARRAYLIST&LT;&G                            t; ();                            Values.add (Keyvalueretrieved.tostring ());                            Values.add (Fieldvalue);                        Params.put (Fieldkey, values);                        } else {((arraylist<string>) keyvalueretrieved). Add (Fieldvalue);                    }} else {params.put (Fieldkey, fieldvalue);        }}} beanutils.populate (t, params); } catch (Instantiationexception | illegalaccessexception |            InvocationTargetException e) {e.printstacktrace ();        Logger.error ("String Convert to Bean failure!", e);    } return t; Do not forget to add a custom converter to the SPRINGMVC. E3: You can also invoke the handler method in theUse the type converter to complete the parsing.    @RequestMapping ("/teststudent") public string Teststudent (@RequestParam ("student") string studentstr, string amount) {    System.out.println ("Studentstr:" + studentstr);    System.out.println ("Amount:" + amount); Return "Success";} Description: For complex data, we can not rely on SPRINGMVC, only with the help of third parties, or ourselves to write the parser to parse. ★ Multiple Form Submission Form data: <form action= "" method= "Post" id= "Form2" > First name:<input type= "text" name= "FirstName" Maxleng Th= "size="/> <br/> last name:<input type= "text" name= "LastName" maxlength= "" size= "/> <br" /> gender:<br/> male:<input type= "Radio" name= "Gender" value= "1"/><br/> female:<input Typ E= "Radio" name= "Gender" value= "0"/><br/> <%–favorite food:<br/> steak:<input type= "checkbox" NA    Me= "Foods" value= "steak"/><br/> pizza:<input type= "checkbox" name= "Foods" value= "Pizza"/><br/> Chicken:<input type= "checkbox" name= "Foods" value= "Chicken"/><br/>–%> <tExtarea wrap= "Physical" cols= "" name= "quote" rows= "5" >enter your favorite quote!</textarea><br/> Sele CT A level of education:<br/> <select name= "Education" > <option value= "Jr.high" >jr.high</op tion> <option value= "HighSchool" >HighSchool</option> <option value= "College" >college&lt ;/option> </select><br/> Select your favorite time of day:<br/> <select size= "3" name= "to        FD "> <option value=" Morning ">Morning</option> <option value=" Day ">Day</option> <option value= "Night" >Night</option> </select> <p><input type= "Submit"/></p&gt ; </form><form action= "" method= "Post" id= "Form1" > First name:<input type= "text" name= "FirstName" MaxLen Gth= "size="/> <br/> last name:<input type= "text" name= "LastName" maxlength= "" size= "/> <b" R/> GENDER:&LT;BR/&GT Male:<input type= "Radio" name= "Gender" value= "1"/><br/> female:<input type= "Radio" name= "gender" value = "0"/><br/> <%–favorite food:<br/> steak:<input type= "checkbox" name= "Foods" value= "Steak"/> <br/> pizza:<input type= "checkbox" name= "Foods" value= "Pizza"/><br/> chicken:<input type= "Check Box "name=" Foods "value=" Chicken "/><br/>–%> <textarea wrap=" physical "cols=" "name=" quote "rows=" 5 "& Gt Enter your favorite quote!</textarea><br/> Select a level of education:<br/> <select name= "Educ ation "> <option value=" Jr.high ">Jr.High</option> <option value=" HighSchool ">highschool& lt;/option> <option value= "College" >College</option> </select><br/> Select your FA Vorite time of Day:<br/> <select size= "3" name= "TOfD" > <option value= "Morning" >morning</opt Ion> <Option Value= "Day" >Day</option> <option value= "Night" >Night</option> </select></fo    RM&GT;E1: You also need to define a Students class: public class Students {private list<student> Students;    Public list<student> getstudents () {return students;    } public void Setstudents (list<student> students) {this.students = students; }} Request: $ (' form '). Submit (function () {$.ajax ({url: "Teststudent", data:JSON.stringify ({"Stud            Ents ": [$ (' #form1 '). SerializeObject (), $ (' #form2 '). SerializeObject () ]}), ContentType: "Application/json;charset=utf-8", type: "Post", Success:function (re        Sult) {Console.log (result);    }    }); return false;}); Handler method: @RequestMapping ("/teststudent") public String teststudent (@RequestBody Students Students) {for (Student Stud Ent:students.getStudents ()) {SYSTEM.OUT.PRIntln ("Student:" + student); } return "Success";} can print normally. E2: No additional classes, that is, do not define students requests: $ (' form '). Submit (function () {$.ajax ({url: "teststudent", Data:JSON.stringi FY ([$ (' #form1 '). SerializeObject (), $ (' #form2 '). SerializeObject ()]), ContentType: "App        Lication/json;charset=utf-8 ", type:" Post ", success:function (Result) {Console.log (result);    }    }); return false;}); Handler method: E21: Receive @requestmapping ("/teststudent") public String teststudent (@RequestBody student[] students) through an array {for (Student student:students)    {System.out.println ("Student:" + student); } return "Success";}   E22: Receive @requestmapping ("/teststudent") public String teststudent (@RequestBody list<student> students) via List {   for (Student student:students) {System.out.println ("Student:" + Student); } return "Success";} ★ One form multiple object form object such as: E1:<form action= "" method= "post" id= "form" > First name:<iNput type= "text" name= "FirstName" maxlength= "All Size=" "/> <br/> last name:<input type=" text "Name=" Lastn Ame "Maxlength=" "size=" "/> <br/> gender:<br/> male:<input type=" Radio "name=" Gender "value=" 1 "/><br/> female:<input type=" Radio "name=" Gender "value=" 0 "/><br/> <%–favorite Food:<br/&    Gt Steak:<input type= "checkbox" name= "Foods" value= "steak"/><br/> pizza:<input type= "checkbox" Name= " Foods "value=" Pizza "/><br/> chicken:<input type=" checkbox "name=" Foods "value=" Chicken "/><br/> –%> <textarea wrap= "physical" cols= "" name= "quote" rows= "5" >enter your favorite quote!</textarea>< Br/> Select a level of education:<br/> <select name= "Education" > <option value= "Jr.high" ; jr.high</option> <option value= "HighSchool" >HighSchool</option> <option value= "College" >College</option>   </select><br/> Select your favorite time of day:<br/> <select size= "3" name= "TOfD" > <option value= "Morning" >Morning</option> <option value= "Day" >Day</option> <opti On value= "Night" >Night</option> </select> first name:<input type= "text" name= "FirstName" maxlength = "Size="/> <br/> last name:<input type= "text" name= "LastName" maxlength= "" size= "/> <br/&"    Gt  Gender:<br/> male:<input type= "Radio" name= "Gender" value= "1"/><br/> female:<input type= "Radio" Name= "gender" value= "0"/><br/> <%–favorite food:<br/> steak:<input type= "checkbox" name= "foods "Value=" Steak "/><br/> pizza:<input type=" checkbox "name=" Foods "value=" Pizza "/><br/> chicken:& Lt;input type= "checkbox" name= "Foods" value= "Chicken"/><br/>–%> <textarea wrap= "Physical" cols= "20" Name= "Quote" rows= "5">enter your favorite quote!</textarea><br/> Select a level of education:<br/> <select name= " Education "> <option value=" Jr.high ">Jr.High</option> <option value=" HighSchool ">highsch ool</option> <option value= "College" >College</option> </select><br/> Select You R favorite time of Day:<br/> <select size= "3" name= "TOfD" > <option value= "Morning" >Morning<    /option> <option value= "Day" >Day</option> <option value= "Night" >Night</option> </select> <p><input type= "Submit"/></p></form>e2:<form action= "method=" POST " > First name:<input type= "text" name= "firstname[0" "maxlength=" [size= "]/> <br/> last Name:<in Put type= "text" name= "lastname[0" "maxlength=" "size=" "/> <br/> gender:<br/> male:<input type=" "Radio" Name= "gender[0]" value="1"/><br/> female:<input type= "Radio" name= "Gender[0" "value=" 0 "/><br/> favorite FOOD:&LT;BR/&G    T Steak:<input type= "checkbox" Name= "foods[0]" value= "Steak"/><br/> pizza:<input type= "checkbox" Name= " Foods[0] "value=" Pizza "/><br/> chicken:<input type=" checkbox "Name=" foods[0] "value=" Chicken "/>< br/> <textarea wrap= "physical" cols= "" Name= "quote[0" "rows=" 5 ">enter your favorite quote!</textarea> <br/> Select a level of education:<br/> <select name= "education[0" "> <option value=" Jr.H IgH ">Jr.High</option> <option value=" HighSchool ">HighSchool</option> <option value=" College ">College</option> </select><br/> Select your favorite time of day:<br/> <se Lect size= "3" name= "Tofd[0" "> <option value=" Morning ">Morning</option> <option value=" Day "     >Day</option>   <option value= "Night" >Night</option> </select> first name:<input type= "text" Name= "FirstName [1] "maxlength=" "size="/> <br/> last name:<input type= "text" name= "lastname[1" "maxlength=" "size=" "/> <br/> gender:<br/> male:<input type=" Radio "name=" gender[1] "value=" 1 "/><br/> Fe Male:<input type= "Radio" name= "gender[1]" value= "0"/><br/> favorite food:<br/> Steak:<input Typ e= "checkbox" Name= "foods[1" "value=" Steak "/><br/> pizza:<input type=" checkbox "Name=" foods[1] "value=" Pizza "/><br/> chicken:<input type=" checkbox "Name=" foods[1] "value=" Chicken "/><br/> <textar  EA wrap= "Physical" cols= "Name=" quote[1] "rows=" 5 ">enter your favorite quote!</textarea><br/> Select A level of education:<br/> <select name= "education[1" "> <option value=" Jr.high ">jr.high</o Ption> <option ValUe= "HighSchool" >HighSchool</option> <option value= "College" >College</option> </select&gt ;<br/> Select your favorite time of day:<br/> <select size= "3" name= "Tofd[1" "> <option V Alue= "Morning" >Morning</option> <option value= "Day" >Day</option> <option value= "nigh T ">Night</option> </select> <p><input type=" Submit "/></p></form> Look at the processed data: E1: (1) json.stringify ($ (' form '). SerializeObject ()): {"FirstName": ["Jack", "Tom"], "lastName": ["AA", " Lily "]," foods ": [" Steak "," Pizza "," Steak "]," quote ": [" Enter your favorite quote! "," Enter your favorite quote! "]," Education ": [" Jr.high "," Jr.high "]," TOfD ": [" Day "," Day "]," gender ":" 1 "} (2) $ (' form '). Serialize (): Firstname=jack &lastname=aa&foods=steak&foods=pizza&quote=enter+your+favorite+quote!&education=jr.high &tofd=day&firstname=tom&lastname=lily&gender=1&foods=steak&quote=enter+your+favorite+quote!&education=jr.high&tofd=day Description: The first type is not processed, and there is no way to tell which object the values in the array belong to. The second way can be handled, but you need to write a custom type converter, which is not described here. If you are interested in children's shoes, explore them yourself. E2: (1) json.stringify ($ (' form '). SerializeObject ()): {"firstname[0]": "AA", "lastname[0]": "BB", "gender[0]": "1", " Foods[0] ":" Pizza "," quote[0] ":" Enter your favorite quote! "," education[0] ":" Jr.high "," tofd[0] ":" Day "," firstname[1] " : "DS", "lastname[1]": "CC", "gender[1": "1", "foods[1]": ["Steak", "Pizza"], "quote[1]": "Enter your favorite quote!", " EDUCATION[1] ":" Jr.high "," tofd[1] ":" Day "} (2) $ (' form '). Serialize (): FIRSTNAME%5B0%5D=AA&AMP;LASTNAME%5B0%5D=BB &gender%5b0%5d=1&foods%5b0%5d=pizza&quote%5b0%5d=enter+your+favorite+quote!&education%5b0%5d= jr.high&tofd%5b0%5d=day&firstname%5b1%5d=ds&lastname%5b1%5d=cc&gender%5b1%5d=1&foods%5b1% 5d=steak&foods%5b1%5d=pizza&quote%5b1%5d=enter+your+favorite+quote!&education%5b1%5d=jr.high& Tofd%5b1%5d=day Description: The first look at the rules can be followed, seemingly can be parsed, but not a standard JSON format of data. The second kind even appeared garbled, did not think analytic method. To take a look at the first, also here is a way of thinking, becauseFor the implementation of the more laborious. Idea: Use regular like This:gson Gson = new Gson (); String jsoninstring = "{\" student[0].firstname\ ": \" asdf\ ", \" student[0].lastname\ ": \" sfd\ ", \" Student[0].gender\ ": \ "1\", \ "student[0].foods\": [\ "Steak\", \ "Pizza\"],\ "student[0].quote\": \ "Enter your favorite quote!\", \ "student[0]. education\ ": \" jr.high\ ", \" student[0].tofd\ ": \" day\ ", \" student[1].firstname\ ": \" sf\ ", \" student[1].lastname\ ": \" Sdf\ ", \" Student[1].gender\ ": \" 1\ ", \" student[1].foods\ ": [\" Pizza\ ", \" chicken\ "],\" student[1].quote\ ": \" Enter Your favorite quote!\ ", \" student[1].education\ ": \" jr.high\ ", \" student[1].tofd\ ": \" Night\ "}"; String jsonwithoutarrayindices = Jsoninstring.replaceall ("\\[\\d\\]", ""). ReplaceAll ("Student.", ""); String jsonascollection = "[" + Jsonwithoutarrayindices + "]"; String jsonasvalidcollection = Jsonascollection.replaceall (", \" Student.firstname\ "", "},{\" student.firstname\ ""); System.out.println (jsonasvalidcollection); Student[] Students = Gson.fromjson (jsonasvalidcollection, Student[].class); System.ouT.println ("-----------------------------------------------"); System.out.println (Students[0]); System.out.println ("-----------------------------------------------");

  

springmvc-Processing of Ajax (with JSON type) (2)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.