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

Source: Internet
Author: User
Tags serialization

First, to understand some of the things. 1. From the client, it is necessary to understand: (1) What format of the JSON data to be sent to the server side of the SPRINGMVC very convenient processing, how to let us write less code, how to do the JSON data and the corresponding between the entity. (2) How these sent data are organized. 2. From the server side, you need to understand: (1) Springmvc How to return JSON data. (2) Springmvc How to handle the complex data requested. Several parameters of 3.$.ajax: (1) Contenttype:contenttype: ' Application/json;charset=utf-8 ', as the request header, to tell the server that the body of the message is a serialized JSON string. In addition to the low version of IE browser, all major browsers natively support Json.stringify () to serialize objects. (2) DataType: The data type that is expected to be returned by the server. 4.SpringMVC is how to handle 5 of the JSON data. The overall idea: (1) Springmvc can be done, as far as possible with the help of SPRINGMVC, rather than our manual to parse. (2) Springmvc can not parse, try to use the third-party Jar package to parse. (3) Springmvc and third-party Jar package can not solve the time, we go to resolve. Second, to understand the first question, the premise is to understand the first question: SPRINGMVC is how to handle the JSON data. 1. Use httpmessageconverter<t> to process JSON data. Spring's httpmessageconverter<t> is responsible for translating the request information into an object and outputting the object as a response message. 2.API (1) Boolean canRead (class<?> Clazz, mediatype mediatype), whether the converter can convert the request information to an object of type Clazz, and supports the specified MIME type, such as: text/ Html,application/json and so on. (2) Boolean canWrite (class<?> Clazz, mediatype mediatype); The converter can write objects of the Clazz type to the response, and the type of the response support is defined in mediatype. (3) List<mediatype> GetsupportedmediAtypes (); Change the mediatype type supported by the converter. (4) T read (class<? extends T> Clazz, Httpinputmessage inputmessage); Converts the request traffic to an object of type Clazz. (5) void write (T T, mediatype ContentType, Httpoutputmessage Outputmessage). Writes an object of type T to the response output stream, specifying mediatype.

3. Implementation class

Spring supports using Jackson to handle JSON problems by default.

The imported Jackson Jar package:

4. Specific Treatment methods: (1) Use @RequestBody and httpentity<t> to process the request. (2) The response is processed using @ResponseBody and responseentity<t>. (3) @RequestBody to annotate the entry of the processing method. (4) @ResponseBody to label the signature of the processing method. (5) Httpentity<t> and responseentity<t> are used as processing methods. The specific usage method is described in the following example. [email protected] and @ResponseBody can be used at the same time. Third, the above briefly describes how SPRINGMVC processing JSON data, and now the second question: What format of JSON data to be sent to the server-side SPRINGMVC very convenient processing, here refers to the request of the JSON string and entity mapping.  Take a simple entity as an example: Person person.java/** * @author Solverpeng * @create 2016-08-12-10:50 */public class Person {private String    Name    Private Integer age;        Public person () {} public person (String name, Integer age) {this.name = name;    This.age = age;    } @NotBlank (message = "Name cannot be empty") public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int Getage () {return age;    public void Setage (int.) {this.age = age;  } @Override Public String toString () {      Return "person{" + "name=" + name + ' \ ' + ", age=" + Age + '} '; }} (1) for a simple person object, we don't even need to use JSON to complete the mapping between the requested data and the entity. Request: $ ("#testJson"). Click (function () {$.ajax ({url: "Testjson", type: "POST", data: {n        AME: "ABC", Age: "All"}, success:function (result) {Console.log (result); }    });});     Handler method: @RequestMapping ("/testjson") public person Testjson (person person) {System.out.println (' person: ' + person); return person;} (2) for the person array, what format needs to be sent to be processed directly by SPRINGMVC? Request: $ ("#testJson6"). Click (function () {$.ajax ({url: "TestJson6", type: "POST", data: ' [{"Name": " Brett "," Age ":" A "}, {" Name ":" Jason "," Age ":" All "}, {" Name ":" Elliotte "," Age ":" $ "}] ', ContentType:" Applicat Ion/json;        Charset=utf-8 ", success:function (Result) {Console.log (result); }    });}); Handler method: @RequestMapping("/testjson6") public String TestJson6 (@RequestBody list<person> persons) {System.out.println ("persons:" + Perso    NS); Return "Success";} Note: (1) You need to specify "ContentType", and note that the requested data sent is not in Form data, but in the request Payload. about [Request Payload], explained later. (2) The @RequestBody must be specified, otherwise it cannot be resolved. The third question: How to organize this data and SPRINGMVC how to handle the data and map it. (1) Description: The two examples mentioned above are just one of the simplest forms. Now expand it, in four, what the SPRINGMVC to do with the data, not just the SPRINGMVC, but also the SPRINGMVC can't handle it, use a third party to handle it, or the third party can't handle it, I'll handle it myself. The data here also refers not only to JSON-type data. (2) For non-form Ajax submissions, this provides only one simple way. Take the person above as an example. E1: organization of data and sending of requests: var personlist = [];p ersonlist.push ({name: "John Doe", Age: "}");p Ersonlist.push ({name: "Zhang San", Age: "12"}); $ ( "#testJson5"). Click (function () {$.ajax ({type: "POST", url: "TestJson5", Data:JSON.stringify (PE  rsonlist),//Serializes the object into a JSON string contentType: ' Application/json;charset=utf-8 ',//Set the request header information Success:function (data) {}, Error:function (res) {}}); Handler method: @RequestMapping ("/testjson5") public StringTestJson5 (@RequestBody list<person> persons) {System.out.println (persons); Return "Success";} (3) Ajax submissions based on forms.    Provides a serialization method: $.fn.serializeobject = function () {var o = {};    var a = This.serializearray (); $.each (A, function () {if (O[this.name]!== undefined) {if (!o[this.name].push) {O[this            . name] = [O[this.name]]; } o[this.name].push (This.value | |        ‘‘); } else {O[this.name] = This.value | |        ‘‘;    }    }); return o;}; There is also a serialization mode: ★ Single-form case: Form: <form action= "" method= "POST" > First name:<input type= "text" name= "FirstName" maxlength= "Size="/> <br/> last name:<input type= "text" name= "LastName" maxlength= "" size= "/> &LT;BR/&G"    T  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/> Chick En:<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= "highs Chool ">HighSchool</option> <option value=" College ">College</option> </select><br/&    Gt Select your favorite time of day:<br/> <select size= "3" name= "TOfD" > <option value= "Morning" >m orning</option> <option value= "Day" >Day</option> <option value= "Night" >night</opt  ion> </select> <p><input type= "submit"/></p></form> corresponding entity: student.java/** * @author Solverpeng * @creaTe 2016-08-16-11:14 */public class Student {private String firstName;    Private String LastName;    Private Integer gender;    Private list<string> Foods;    Private String quote;    Private String education;    Private String TOfD;    Public String Getfirstname () {return firstName;    } public void Setfirstname (String firstName) {this.firstname = FirstName;    } public String Getlastname () {return lastName;    } public void Setlastname (String lastName) {this.lastname = LastName;    } public Integer Getgender () {return gender;    } public void Setgender (Integer gender) {This.gender = gender;    } public list<string> Getfoods () {return foods;    } public void Setfoods (List<string> foods) {this.foods = foods;    } public String GetQuote () {return quote;    } public void Setquote (String quote) {this.quote = quote; } public String Geteducation () {REturn education;    } public void Seteducation (String education) {this.education = education;    } public String Gettofd () {return tOfD;    } public void Settofd (String tOfD) {this.tofd = TOfD;                } @Override Public String toString () {return ' student{' + ' firstname= ' + firstName + ' \ ' + ", lastname= '" + lastName + "\" + ", gender=" + Gender + ", foods=" + foods + ", quote= '" + quote + "\" + ", education= ' + education + ' \ ' +", tofd= '    + TOfD + ' \ ' + '} '; }}e1: Use SerializeObject () to serialize the value: Json.stringify ($ (' form '). SerializeObject ()): {"FirstName": "Jack", "LastName": " Lily "," Gender ":" 1 "," Foods ": [" Pizza "," Chicken "]," quote ":" Hello Hello "," Education ":" Jr.high "," TOfD ":" Day "} Request: $ ( Function () {$ (' form '). Submit (function () {$.ajax ({url: "teststudent", Data:JSON.strin Gify ($ (' form '). SerializeObject ()), ContentType: "Application/json;charset=utf-8", type: "Post", success:funct            Ion (Result) {Console.log (result);        }        });    return false; });}); E11:SPRINGMVC self-processing handler method: @RequestMapping ("/teststudent") public String teststudent (@RequestBody Student Student    ) {System.out.println (student); Return "Success";} E12: A third-party Jar package is introduced for processing. Prepare: Import the sl4j jar package while adding the Jsonutil tool class. Jsonutil.javapublic Final class Jsonutil {private static final Logger Logger = Loggerfactory.getlogger (Jsonutil.class)    ;    private static final Objectmapper Object_mapper = new Objectmapper ();        /** * Convert POJO to JSON */public static <T> string ToJson (T obj) {string JSON;        try {json = object_mapper.writevalueasstring (obj);            } catch (Jsonprocessingexception e) {logger.error ("convert POJO to JSON failure", e);        throw new RuntimeException (e); } return JSON }/** * Convert JSON to POJO */public static <T> T Fromjson (String JSON, class<t> type) {T P        Ojo        try {Pojo = Object_mapper.readvalue (JSON, type);            } catch (IOException e) {logger.error ("convert JSON to POJO failure", e);        throw new RuntimeException (e);    } return Pojo; }} Back-end Processing: @RequestMapping ("/teststudent") public String teststudent (@RequestBody String inputbody) {Student Student = Json    Util.fromjson (Inputbody, Student.class);    SYSTEM.OUT.PRINTLN (student); Return "Success";} Can print Student objects normally. E2: Use Serialize () to serialize the value: $ (' form '). Serialize (): Firstname=jack&lastname=lily&gender=1&foods=pizza &foods=chicken&quote=hello+hello&education=jr.high&tofd=day Request: $ (function () {$ (' form '). Submit ( function () {$.ajax ({url: "teststudent", Data: $ (' form '). Serialize (), type: "P          Ost ", success:function (Result) {      Console.log (result);        }        });    return false; });});    Handler method: @RequestMapping ("/teststudent") public String teststudent (Student Student) {System.out.println (Student); Return "Success";} You can print Student objects normally. E1 and E2 Comparison Note: E1 submitted JSON data, E2 submitted is not JSON format data. The request parameters of the E1 are stored in [request Payload], and the request parameters of the E2 are stored in Form Data. ★ Single Form complex data form or Student form above, but added outside the form: <span id= "Amount" >33</span> requirements: Send form data via Ajax while sending "amount". After testing, it is straightforward to say the conclusion. Conclusion: This data can not be specified as "Contenttype:application/json", otherwise the backend SPRINGMVC or third-party jar package cannot be parsed automatically, which increases the complexity of parsing, so the JSON string is passed into the background and parsed in the background.            E1:serializeobject () Request: $ (function () {$ (' form '). Submit (function () {$.ajax ({url: "Teststudent", Data: {Amount: $ ("#amount"). Text (), Student:JSON.stringify ($ (' form '). Serializeo Bject ())}, type: "Post", success:function (Result) {Console.log (Resul            T);        }        });  return false;  });}); Backend Processing: Use third-party tool classes to parse @requestmapping ("/teststudent") public string Teststudent (@RequestParam ("student") string    STUDENTSTR, String amount) {Student Student = Jsonutil.fromjson (Studentstr, Student.class);    System.out.println ("Student:" + student);    System.out.println ("Amount:" + amount); Return "Success";} can print normally.            E2:serialize () Request: $ (function () {$ (' form '). Submit (function () {$.ajax ({url: "Teststudent",            Data: {Amount: $ ("#amount"). Text (), Student: $ (' form '). Serialize ()},            Type: "Post", success:function (Result) {Console.log (result);        }        });    return false; });}); Handler method: E1: Try to get Springmvc to parse: @RequestMapping ("/teststudent") public String teststudent (@RequestParam ("Student")    Student Student, String amount) {System.out.println ("Student:" + Student);    System.out.println ("Amount:" + amount); Return "Success";} Result: The request could not reach the handler method E2: @RequestMapping ("/teststudent") public String teststudent (Student Student, string amount) {System.out.println ("    Student: "+ student);    System.out.println ("Amount:" + amount); Return "Success";} Result: The request can reach the target Handler method normally, but the Student object cannot be mapped. Scenario: Self-parsing, writing a custom type converter: public class String2studentconverter implements Converter<string, student>{@Override Publ    IC Student convert (String source) {return injectutil.convert2obj (source, Student.class); }}

  

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

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.