This article introduces the method of receiving json data in spring mvc through code examples. The specific details are as follows:
Receive JSON
Using the @RequestBody annotation on the frontend only requires you to submit a formatted JSON to the Controller, and Spring will automatically assemble it into a bean.
1) On the basis of using the first method to return JSON in the above project, add the following method:
Java code
@RequestMapping(value="/add",method=RequestMethod.POST, headers = {"content-type=application/json","content-type=application/xml"}) @ResponseBody public Object addUser(@RequestBody User user) { System.out.println(user.getName() + " " + user.getAge()); return new HashMap<String, String>().put("success", "true"); }
The POJO here is as follows:
Java code
public class User { private String name; private String age; //getter setter }
2) In the frontend, we can use jQuery to process JSON. From here, I got a jQuery plug-in that can return a form's data into a JSON object:
Js code
$.fn.serializeObject = function(){ var o = {}; var a = 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 || ''; } }); return o; };
The following is the code for receiving and sending JSON using jQuery:
Js code
$(document).ready(function(){ jQuery.ajax({ type: 'GET', contentType: 'application/json', url: 'jsonfeed.do', dataType: 'json', success: function(data){ if (data && data.status == "0") { $.each(data.data, function(i, item){ $('#info').append("姓名:" + item.name +",年龄:" +item.age); }); } }, error: function(){ alert("error") } }); $("#submit").click(function(){ var jsonuserinfo = $.toJSON($('#form').serializeObject()); jQuery.ajax({ type: 'POST', contentType: 'application/json', url: 'add.do', data: jsonuserinfo, dataType: 'json', success: function(data){ alert("新增成功!"); }, error: function(){ alert("error") } }); }); });
But it seems that using Spring is really a troublesome thing. Compared with Jersey’s implementation of RESTful, there are indeed many things that are not concise.
The above is the relevant information about Spring mvc receiving json data shared in this article. I hope you like it.