「Spring MVC」@ResponseBodyでJsonデータを受け付けるサンプルコード
1.Javaコード
@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");
}
public class User {
private String name;
private String age;
//getter setter
}
2.jQueryコード
$(document).ready(function(){
jQuery.ajax({
type: 'GET’,
contentType: 'application/json’,
url: 'jsonback.do’,
dataType: 'json’,
success: function(data){
if (data && data.status == “0") {
$.each(data.data, function(i, item){
$('#info’).append(“name:" + item.name +",age:" +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(“add data success");
},
error: function(){
alert(“error")
}
});
});
});