使用springmvc时,我们在配置可控制器,并且从V层传送自定义类型数据时,在控制器形参中定义自定义类型接收,如下Student形参
@RequestMapping(name="/maptest.do")
@ResponseBody
public Object mapTest(Student student){
System.out.println(student);
Map<String, Student> map = new HashMap<>();
map.put("student1", new Student("张三",21));
map.put("student2", new Student("李四",21));
return map;
}
在V层中,定义AJAX进行数据交互,如下
$(function(
$("#btn3").click(function(){
$.ajax({
url:"maptest.do",
data:{"name":"江湖","age":"20"},//name、age与student的属性是一致的,数值会传递到student的name和age中
success:function(data){
alert(data.student1.name+":"+data.student1.age);
alert(data.student2.name+":"+data.student2.age);
$("#div").empty().append(data.student2.name+":"+data.student2.age);
}
});
});
问题,由于控制器 public Object mapTest(Student student)中的student默认调用无参数构造器,所以在Student类中未定义无参构造器就会报java.lang.NoSuchMethodException <init>()错误