如何在Spring MVC表单中设置所选值:从控制器中选择?

11 forms spring 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我视图中的选择表单字段:

<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>
Run Code Online (Sandbox Code Playgroud)

我的理解是,表单支持bean将根据表单中的modelAttribute属性进行映射.我显然在这里遗漏了一些东西.

小智 11

看来问题与我的设置无关.问题是itemValue被设置为company id属性,而对我的表单支持bean上的公司名称属性进行了比较.所以两者并不相等,因此没有选择任何项目.

上面的代码工作得很好,并且在userForm中为特定属性设置值将在select表单字段中将该值设置为选中,只要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>
Run Code Online (Sandbox Code Playgroud)


Aym*_*bsi 8

最简单的解决方案是覆盖模型类中的toString()方法.在这种情况下,只需通过覆盖toString()来更改类UserForm,如下所示:

@Override
public String toString() {
    return this.getCompanyName();
}
Run Code Online (Sandbox Code Playgroud)

然后Spring会自动在表单中选择正确的值:option


Dar*_*ner 6

我在同一个问题上挣扎了一段时间.这是我的选择字段

<form:select path="origin" items="${origins}" itemValue="idOrigin" itemLabel="name" />
Run Code Online (Sandbox Code Playgroud)

由于我的实体有一个PropertyEditor,我写不出像

<form:select path="origin.idOrigin" items="${origins}" itemValue="idOrigin" itemLabel="name" />
Run Code Online (Sandbox Code Playgroud)

工作正常,但没有被PropertyEditor解析.

因此,考虑到Spring需要确定实体之间的相等性,我只使用idOrigin属性在我的Origin实体中实现了equals和hashcode,并且它起作用了!


NIr*_*odi 6

你也可以这样试试

<form:select id="selectCategoryId" path="categoryId"
      class="selectList adminInput admin-align-input" multiple="">
      <option value="0">-- Select --</option>
      <c:forEach items="${categories}" var="category">
            <option <c:if test="${category.key eq workflowDTO.categoryId}">selected="selected"</c:if>    value="${category.key}">${category.value} </option>
        </c:forEach>
</form:select>
Run Code Online (Sandbox Code Playgroud)