如何在 spring MVC 中将对象和 hashmap 传递给模型属性,以便我可以同时使用它们?

我正在尝试创建一个“添加员工表单”,其中包含用户可以填写的基本属性,例如姓名性别电子邮件等


在表单中,将为可用的部门提供下拉选项,其中列表将由将从控制器发送的 linkedhashmap 预先填充


我已经在我的模型中添加了一个属性对象类型“Employee”,所以当我填写表格时


并返回控制器,员工对象将自动设置


Controller.java


@GetMapping("/showFormForAdd")


public String showFormForAdd(Model theModel) {


    //fetch new list(if any) of departments added

    List<Department> theDepartments = departmentService.getDepartments();


    //Create a linkedhash map to hold our department_id-department name information

    final LinkedHashMap<Integer, String> departmentOptions = departmentService.generateDepartmentOptions(theDepartments);




    // create new employee object and attach to our model atrribute.


            //how to add multiple objects?? doing this so i can pre-populate available departments for selection

    theModel.addAttribute("employee", departmentOptions);



    Employee theEmployee = new Employee();

            //how to add multiple objects?? doing this so when program return control to controller it will help me set the attribute of employees so I can save it into the database

    theModel.addAttribute("employee", theEmployee);



    return "customer-form";

}

问题:我如何将多个属性(例如,员工对象和 linkedhashmap)添加到我的模型中,以便我可以预填充选择框,同时为我的控制器提供方法来为我的员工对象设置属性并保存到我的当我将控制权返回给控制器时数据库?


任何帮助将不胜感激..谢谢!


编辑:只是一个更新,提供的每个答案都有效..我被混淆了。


largeQ
浏览 76回答 2
2回答

烙印99

不要使用相同的键来添加不同的对象,而是对不同的对象使用不同的键,例如://use key "departmentOptions" for LinkedHashMaptheModel.addAttribute("departmentOptions", departmentOptions);Employee theEmployee = new Employee();//use key "employee" for employee objecttheModel.addAttribute("employee", theEmployee);

侃侃尔雅

如果我做对了(来自你的代码评论)//如何添加多个对象??这样做是为了我可以预先填充可供选择的可用部门您只需为 modelAttribute 中的每个对象设置不同的名称。在您的代码中,您两次使用相同的名称,因此该departmentOptions employee对象将被后面的employee对象替换。为了克服这个问题,只需设置它们的唯一名称,您就可以发送对象列表或不同的单一类型对象,例如:// 将多个对象添加到 modelAttribute。theModel.addAttribute("departmentOptions", departmentOptions);Employee theEmployee = new Employee();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;theModel.addAttribute("employee", theEmployee);-----theModel.addAttribute("anotherObject", anotherObject);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java