如何以Spring MVC形式设置所选值:从控制器中选择?
问题内容:
在我的控制器中:
@Controller
public class UserController {
@RequestMapping(value="/admin/user/id/{id}/update", method=RequestMethod.GET)
public ModelAndView updateUserHandler(@ModelAttribute("userForm") UserForm userForm, @PathVariable String id) {
Map<String, Object> model = new HashMap<String, Object>();
userForm.setCompanyName("The Selected Company");
model.put("userForm", userForm);
List<String> companyNames = new ArrayList<String>();
companyNames.add("First Company Name");
companyNames.add("The Selected Company");
companyNames.add("Last Company Name");
model.put("companyNames", companyNames);
Map<String, Map<String, Object>> modelForView = new HashMap<String, Map<String, Object>>();
modelForView.put("vars", model);
return new ModelAndView("/admin/user/update", modelForView);
}
}
我认为选择表单字段:
<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="id" itemLabel="companyName" />
</form:form>
据我了解,表单支持bean将基于表单中的modelAttribute属性进行映射。我显然在这里错过了一些东西。
问题答案:
看来问题与我的设定无关。问题在于,itemValue设置为公司id属性,而对窗体支持bean上的公司名称属性进行了比较。因此,两者不相等,因此没有选择任何项目。
上面的代码可以正常工作,并且在userForm中为特定属性设置值将把该值设置为在选择表单字段中选择的值,只要items集合中一项的值等于表单值即可。我更改了表单字段,使其看起来像这样,它提取了CompanyName而不是ID。
<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="companyName" itemLabel="companyName" />
</form:form>