我有一个场景,我想在spring中使用ajax 将数据绑定到模型类
型号类别:EmployeeBean
private List<FamilyBean> familyDetails;
private String name;
//Getters and setters
FamilyBean课堂在这里:
private String memberId;
private String empUserId;
private String relationship;
private String memberName;
private String age;
private String occupation;
private String contact;
private String isIncludeMedIns;
private String modefiedBy;
private String modifiedOn;
//Getters and Setters
JSP:
<input type="text" name="familyDetails[0].relationship" value="A">
<input type="text" name="familyDetails[0].memberName" value="B">
<input type="text" name="familyDetails[0].age" value="C">
<input type="button" value="Previous" name="_target1" id="previous">
Ajax调用:
$("#previous").click(function(){
$.ajax({
type: "POST",
url:"saveTempEmployeeData",
data:$("#formData").serialize(),//formData is id of the form
success:function (map) {
//alert("SUCCESS");
},
error:function (xhr) {
//alert(xhr.statusText+" ERROR");
}
});
});
弹簧控制器:
@RequestMapping(value="/saveTempEmployeeData", method=RequestMethod.POST, headers="Accept=*")
public @ResponseBody void saveTempEmployeeData(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("employeeBean")EmployeeBean employeeBean, ModelMap map) throws Exception{
userService.saveTempEmployeeData(employeeBean, pageNumber);
try{
System.out.println("In controller");
}
catch(Exception e){
}
response.setContentType("application/json");
response.setCharacterEncoding("ISO-8859-1");
response.getWriter().write(new Gson().toJson(map));
}
数据未绑定到控制器中的模型属性。
有什么办法吗?
N.B:<input type="text" name="name" value="Sunny">
这些数据正在绑定到模型。
我认为您应该在JSP中命名您的输入控件,如下所示:
<input type="text" name="employeeBean.familyDetails[0].relationship" value="A">
<input type="text" name="employeeBean.familyDetails[0].memberName" value="B">
<input type="text" name="employeeBean.familyDetails[0].age" value="C">
这样,Spring就会知道它必须在employeeBean
中填充familyDetails
。
@ModelAttribute("employeeBean")EmployeeBean employeeBean
这就是问题所在。我把它改成:
@ModelAttribute EmployeeBean employeeBean
现在一切都很好。
感谢大家的支持。