使用spring mvc中的ajax将列表数据绑定到模型

时间:2016-04-12 05:57:47

标签: java ajax spring spring-mvc

我有一个场景,我希望在春天使用ajax

将数据绑定到Model Class

模型类:EmployeeBean

private List<FamilyBean> familyDetails;
private String name;
//Getters and setters

FamilyBean Class在这里:

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 Call:

$("#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");
            }
        }); 
    });

Spring Controller:

@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">

此数据与模型绑定。

2 个答案:

答案 0 :(得分:0)

我认为您应该在JSP中为输入控件命名,如下所示:

familyDetails

这样Spring会知道必须在employeeBean内填充 @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); Log.d("Day", "Day" + (c.get(Calendar.DAY_OF_MONTH) - 1)); c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), (c.get(Calendar.DAY_OF_MONTH)) - 1); DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day - 1); dialog.getDatePicker().setMaxDate(c.getTimeInMillis()); return dialog; }

答案 1 :(得分:0)

@ModelAttribute("employeeBean")EmployeeBean employeeBean

这就是问题所在。我改成了:

@ModelAttribute EmployeeBean employeeBean

现在一切正常。

谢谢大家的支持。