表单验证失败后,Combobox不会填充 - Spring 3 MVC

时间:2012-01-18 07:43:36

标签: spring-mvc

我正在使用Spring mvc作为我的Web应用程序。我有一个简单的表单,包含一些文本字段和组合框。

问题:我正在提交包含空值的表单,并执行验证。由于存在空值,因此验证再次显示该表单,但使用空白组合框。当表单第一次显示时,一切正常。

这是代码。如何用最后选择的值填充它们?

查看文件

<form:form method="post" modelAttribute="screening">

<table>
<!-- Text Form -->
    <tr>
        <td>EPI ID</td>
        <td><form:input path="epi_Id" /></td>
        <td><form:errors path="epi_Id" cssClass="error" /></td>
    </tr>

    <tr>
    <!-- Combo-Box -->
        <td>Enrollment Center</td>            
        <td>
            <form:select path="enrollmentCenter">
            <form:options items="${epiCentersList}" itemValue="centerID" itemLabel="name"/>
            </form:select>
        </td>

        <td><form:errors path="enrollmentCenter" cssClass="error" /></td>
    </tr>

    <tr>
        <td colspan="3"><input type="submit" /></td>
    </tr>
</table>

</form:form>

CONTROLLER

@Controller
@RequestMapping("/ScreeningForm")
@SessionAttributes("screening")

public class ScreeningFormController {

@RequestMapping(method=RequestMethod.GET)
public String setupForm(Model model)
{
    ScreeningDomain screen=new ScreeningDomain();
    model.addAttribute("screening", screen);        
    model.addAttribute("epiCentersList", usc.getAllEpiCentersList());
    return "ScreeningForm";
}

@RequestMapping(method=RequestMethod.POST)
public String submitForm(@ModelAttribute("screening") ScreeningDomain screeningDomain, BindingResult result, SessionStatus status)
{
    ScreeningServiceImpl screenService = new ScreeningServiceImpl();
    screeningValidator.validate(screeningDomain, result);
    if (result.hasErrors())
    {
        UtilityServiceClass usc=new UtilityServiceClass();
        model.addAttribute("epiCentersList", usc.getAllEpiCentersList());
        model.addAttribute("screening", screeningDomain);
        return "ScreeningForm";
    }
    else
    {
        screenService.add(screeningDomain);
        return "redirect:ScreeningForm";
    }
}

}

其他一切都很好。 我的模型是丢失列表对象“epiCentersList”值,但我无法弄清楚原因。

1 个答案:

答案 0 :(得分:4)

在您要验证表单数据的控制器方法中,您需要添加 使用以下命令在模型对象中再次列出:

if(result.hasErrors()) {
    model.addAttribute("YourListName",yourList);
    return "inputForm";
}