为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

largeQ 2022-12-21 12:45:25
我正在尝试创建一个“添加员工表单”,其中包含用户可以填写的基本属性,例如姓名性别电子邮件等在表单中,将为可用的部门提供下拉选项,其中列表将由将从控制器发送的 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)添加到我的模型中,以便我可以预填充选择框,同时为我的控制器提供方法来为我的员工对象设置属性并保存到我的当我将控制权返回给控制器时数据库?任何帮助将不胜感激..谢谢!编辑:只是一个更新,提供的每个答案都有效..我被混淆了。
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

不要使用相同的键来添加不同的对象,而是对不同的对象使用不同的键,例如:


//use key "departmentOptions" for LinkedHashMap

theModel.addAttribute("departmentOptions", departmentOptions);


Employee theEmployee = new Employee();

//use key "employee" for employee object

theModel.addAttribute("employee", theEmployee);


查看完整回答
反对 回复 2022-12-21
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

如果我做对了(来自你的代码评论)


//如何添加多个对象??这样做是为了我可以预先填充可供选择的可用部门


您只需为 modelAttribute 中的每个对象设置不同的名称。在您的代码中,您两次使用相同的名称,因此该departmentOptions employee对象将被后面的employee对象替换。为了克服这个问题,只需设置它们的唯一名称,您就可以发送对象列表或不同的单一类型对象,例如:


// 将多个对象添加到 modelAttribute。


theModel.addAttribute("departmentOptions", departmentOptions);

Employee theEmployee = new Employee();         

theModel.addAttribute("employee", theEmployee);

-----

theModel.addAttribute("anotherObject", anotherObject);


查看完整回答
反对 回复 2022-12-21
  • 2 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信