今天在看视频学写springboot项目web开发,用Map集合做的一个临时数据库,键值对为<Integer,Object>,由于疏忽,没有把Integer的id值和Object里定义的id值相对应,导致在前端用Restful取id参数传到后端来调用Map集合的get方法的时候找不到对应的对象,返回了null。
static{
employees = new HashMap<Integer, Employee>(); //创建一个员工表
employees.put(1001,new Employee(1001,"bejav","2823266419@qq.com",1,new Department(101,"后勤部")));
employees.put(1002,new Employee(1002,"bejac","2823266419@qq.com",0,new Department(102,"后勤部")));
employees.put(1003,new Employee(1003,"bejad","2823266419@qq.com",1,new Department(103,"后勤部")));
employees.put(1004,new Employee(1004,"bejae","2823266419@qq.com",0,new Department(104,"后勤部")));
employees.put(1005,new Employee(1005,"bejaa","2823266419@qq.com",1,new Department(105,"后勤部")));
}
//通过id查询员工
public Employee getEmployeeById(Integer id){
return employees.get(id);
}
上面是dao层写的临时数据库以及对应方法
下面是Controller层写的调用
//去员工的修改页面
@GetMapping("/updateEmployee/{id}") //链接都是用GetMapping
public String toUpdateEmployee(@PathVariable("id") Integer id,Model model){
System.out.println("id->"+id); //id能传到
Employee employee = employeeDao.getEmployeeById(id);
System.out.println("employee>"+employee); //传入空值?get一个不存在的值,不会抛出异常,获得的返回值为null。
model.addAttribute("empid",employee);
//查出所有部门的信息
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/update";
}
通过排错,找到出错原因是因为employeeDao.getEmployeeById(id)这个方法没有返回值,也就是null,那么刨根到底就是dao层的get()方法没有找到值,所以就找到了原因。