Spring MVC and jquery Ajax

Source: Internet
Author: User

In Spring MVC3, it is convenient to respond and accept JSON.
Using the annotation @responsebody, you can convert the results (a map containing strings and JavaBean) to JSON.
Using @RequestBody annotations The foreground only needs to submit a conforming json,spring to the Controller that will automatically assemble it into a bean.

Spring this transformation is implemented by the Org.codehaus.jackson component, all of which require the introduction of JACKSON-CORE-ASL and Org.codehaus.jackson two jar packages

<title>spring Mvc</title><script type="Text/javascript"Src="Http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type="Text/javascript"Src="Http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script><script type="Text/javascript"Src="<%=request.getcontextpath ()%>/scripts/user/index.js"></script>"Info"></div><form action="Add"Method="Post"Id="form">Number:<input type="text"Name="ID"/>Name:<input type="text"Name="username"/>Age:<input type="text"Name=" Age"/><input type="Button"Value="Submit"Id="Submit"/></form></body>

HTML file path: .../webapp/views/index.html

//returning data from a form to a JSON object$.fn.serializeobject =function () {varo = {}; varA = This. Serializearray (); $.each (A, function () {if(o[ This. Name]) {      if(!o[ This. Name].push) {o[ This. name] = [o[ This. Name]]; } o[ This. Name].push ( This. value | |"'); } Else{o[ This. Name] = This. value | |"';  }  }); returno;}; $ (document). Ready (function () {Jquery.ajax ({type:'GET', ContentType:'Application/json', URL:'user/list', DataType:'JSON', Success:function (data) {if(data && data.success = ="true") {            $('#info'). HTML ("Total"+ Data.total +"Bar data. <br/>"); $.each (Data.data, function (I, item) {$ ('#info'). Append ("Number:"+ Item.id +", Name:"+Item.username+", Age:"+item.age);          }); }}, Error:function () {alert ("Error")        }      }); $("#submit"). Click (function () {varJsonuserinfo = $.tojson ($ ('#form'). SerializeObject ());        alert (jsonuserinfo); Jquery.ajax ({type:'POST', ContentType:'Application/json', URL:'User/add', Data:jsonuserinfo, DataType:'JSON', Success:function (data) {alert ("New Success! "); }, Error:function (data) {alert ("Error")          }        });    }); });
@Controller @requestmapping ("/user") Public classDemocontroller {PrivateLogger Logger = Loggerfactory.getlogger (Democontroller.class); @RequestMapping (Value="/list", method =requestmethod.get) @ResponseBody PublicMap<string, object>getuserlist () {Logger.info ("List"); List<UserModel> list =NewArraylist<usermodel>(); Usermodel um=NewUsermodel (); Um.setid ("1"); Um.setusername ("SSS"); Um.setage (222);    List.add (UM); Map<string, object> modelmap =NewHashmap<string, Object> (3); Modelmap.put (" Total","1"); Modelmap.put ("Data", list); Modelmap.put ("Success","true"); returnModelmap; } @RequestMapping (Value="/add", method =requestmethod.post) @ResponseBody PublicMap<string, string>AddUser (@RequestBody Usermodel model) {Logger.info ("New"); Logger.info ("capture the model that was passed to the foreground, with the name:"+model.getusername ()); Map<string, string> map =NewHashmap<string, String> (1); Map.put ("Success","true"); returnmap; }}

Another way to transfer parameters

Front-End Code:

$.ajax ({type: "POST",

           " ASSIGN.V " ,            data: {               Userid:userid,               'add[]' : [1,2 ,3],               'del[]' : [4]           },           Success:function (data) {               searchwidget.searchuser (1);               }    });

Back-End Code:

@ResponseBody @RequestMapping (value="/assign", Method=requestmethod.post) PublicString Assign (@RequestParam (value="userId", required=true)intuserId, @RequestParam (value="add[]", required=false)int[] Add, @RequestParam (value="del[]", required=false)int[] del) {System. out. println ("userId:"+userId); System. out. println ("Add:"+add); System. out. println ("del:"+del); return ""; }

Spring MVC and jquery ajax

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.