index.jsp
<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><% StringPath=Request.getcontextpath ();%><HTML><Scripttype= "Text/javascript"src= "<%=request.getcontextpath ()%>/script/jquery-1.7.2.min.js"></Script><Scripttype= "Text/javascript"src= "<%=request.getcontextpath ()%>/script/jquery.json-2.4.js"></Script><Scripttype= "Text/javascript"src= "<%=request.getcontextpath ()%>/script/jquery.form.js"></Script><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title><Scripttype= "Text/javascript">functiontest_2 () {varPostURL= "<%=request.getcontextpath ()%>/jsoncontroller/receive_jsondata_2?date="+NewDate ()+""; //the 2nd simple method varFormData=JQuery ("#json_form2"). Serializearray (); //converts this array to a JSON object. varJsondata=Convertarray (FormData); //the JSON object is converted to a string before it can be sent. varJsondatastr=Jquery.tojson (Jsondata); Jquery.ajax ({//RequestType:"POST", Url:posturl, Data:jsondatastr, ContentType:"Application/json", //returnDataType:"JSON", Success:function(msg) {alert ("Data Saved:" +msg); } }); }functionConvertarray (o) {//This function is mainly recommended. It converts the jquery serialized value to the Name:value form. varv= {}; for (varIincho) {if (typeof(V[o[i].name])== 'undefined') V[o[i].name]=O[i].value; ElseV[o[i].name]+= "," +O[i].value; } returnv;} </Script></Head><Body> <formMethod= "POST"ID= "Json_form2"Action=""> <inputtype= "text"name= "Dogid"ID= "Dogid"value= "User name"/> <inputtype= "text"name= "Dogname"ID= "Dogname"value= "check box 1"/> <inputtype= "button"value= "Send is a JSON string"onclick= "test_2 ();"/> </form> </Body></HTML>
Controller
/** * 2 ways to receive JSON objects in spring * REQUESTB Ody Dogbean Dogbean * Does not add requestbody, indicating that a normal get or POST request is received, and the parameters in the request are consistent with the attributes in the bean. Beans can be received. * * Plus requestbody, which means that a JSON string is received for request data, and spring automatically turns the JSON string into a JSON object. * * */ @RequestMapping (Value = "/receive_jsondata_2" ) public String receive_jsondata_2 (@RequestBody dogbean dogbean) {System.out.println ( "Dogbean =" + Dogbean); System.out.println (Dogbean.getdogid () + "\ T" + Dogbean.getdogname ()); return null ; }
- If this is not @RequestBody , then the parameters in the request cannot be encapsulated in Dogbean because the data format in request is in JSON format, and the auto-encapsulated format is "dogid=1& Dogname=dog1 "This format can be automatically encapsulated.
(ix) SPRINGMVC JSON data request (client sends JSON data to server)