我有一个简单的 POJO Java 类(未显示 getter 和 setter)
public class VacationInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date vacationFrom;
@Temporal(TemporalType.TIMESTAMP)
private Date vacationTo;
,带有下一个方法的 Spring MVC Controller
@RequestMapping(value = "updateVacations", method = RequestMethod.POST)
public String updateVacations(@RequestParam VacationInfo[] vacationInfos) {
...
}
和 jQuery post 请求
$.ajax({
type: "POST",
url: "updateVacations",
dataType: 'json',
data: vacationInfos
});
其中“vacationInfos”是一个包含 JSON 对象的数组,它代表 VacationInfo 类:
[
{
vacationFrom: "01-01-2013",
vacationTo: "01-01-2013"
},
{
vacationFrom: "01-01-2013",
vacationTo: "01-01-2013"
}
]
但是当我请求时 - 我收到了 HTTP 400 错误。
最佳答案
编写此代码是为了获取所有已检查的表单并将它们全部发布到 Spring Controller
jquery 方法::
$('#testButton').click(function(){
var testList= [];
$('.submit').filter(':checked').each(function() {
var checkedFrom= $(this).closest('form');
var testPojo= checkedFrom.serializeObject();
testList.push(testPojo);
});
$.ajax({
'type': 'POST',
'url':"testMethod",
'contentType': 'application/json',
'data': JSON.stringify(testList),
'dataType': 'json',
success: function(data) {
if (data == 'SUCCESS')
{
alert(data);
}
else
{
alert(data);
}
}
});
});
而jquery提供了两个级别的序列化,例如serialize()和serializeArray()。但这是序列化的自定义方法
用户定义的对象。
$.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;
};
在 Spring Controller 中
@RequestMapping(value = "/testMethod", method = RequestMethod.POST)
public @ResponseBody ResponseStatus testMethod(HttpServletRequest request,
@RequestBody TestList testList)
throws Exception {
..............
}
其中 TestList 是另一个类,编写用于处理表单发布,并在 mvc Controller 中使用 Test 数组来处理测试方法
public class TestList extends ArrayList<Test> {}
关于java - Spring MVC 和 jquery post 请求与 POJO 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459171/