本文示範如何在 Spring MVC 中接收 JSON 資料,並搭配 jQuery 將表單內容序列化後送出。
使用 RequestBody 時,前端只需提交符合格式的 JSON,Spring 就會自動拼裝成 Java 物件。
@RequestMapping(value = "/add", method = RequestMethod.POST, headers = {"content-type=application/json"})
@ResponseBody
public Map addUser(@RequestBody User user) {
System.out.println(user.getName() + " " + user.getAge());
Map result = new HashMap();
result.put("success", "true");
return result;
}
對應的 User 物件可包含 name 與 age 屬性,並提供 getter 與 setter。
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
可使用 jQuery 將表單轉成物件。
$.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;
};
$("#submit").click(function() {
var jsonuserinfo = JSON.stringify($('#form').serializeObject());
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'add.do',
data: jsonuserinfo,
dataType: 'json',
success: function(data) {
alert('新增成功');
},
error: function() {
alert('請求失敗');
}
});
});
透過 RequestBody 與 jQuery 的組合,可以讓表單資料以 JSON 格式傳到後端,再由 Spring 自動轉為物件,減少手動解析字串的負擔。