Spring MVC:<form:select>选项不会保持选中状态</form:select>

时间:2014-01-29 16:31:20

标签: spring-mvc select

我有一个简单的表格来添加新老师。我在我的视图中使用Spring <form:select>来显示教师标题的列表,但是当我选择一个选项而没有输入教师的名字和/或姓,因为我正在验证所有三个字段,当提交后加载页面,先前选择的选项会丢失,并再次显示“选择标题”文本。

这是控制器:

@RequestMapping(value="/add", method = RequestMethod.POST)
public String postAddTeacher(@RequestParam(value = "title") Integer titleId, 
        @Validated(Teacher.TeacherChecks.class) @ModelAttribute("teacherAttribute") Teacher teacher,
        BindingResult result,
        Model model) {

    logger.debug("Received request to add new teacher");

    if (result.hasErrors()) {
        if (titleId != null) {
            model.addAttribute("titleList", titleService.getAll());
            Title title = titleService.get(titleId);
            teacher.setTitle(title);
            model.addAttribute("teacher", teacher);
            return "addTeacher";
        }
        else {
            model.addAttribute("titleList", titleService.getAll());
            return "addTeacher";
        }
    }
    else {
        teacherService.add(titleId, teacher);
        return "success/addTeacherSuccess";
    }
}

这是观点:

<c:url var="saveUrl" value="/essays/main/teacher/add" />
<form:form modelAttribute="teacherAttribute" method="POST" action="${saveUrl}">
<form:errors path="*" cssClass="errorblock" element="div" />

<form:label path="title"></form:label>
<form:select path="title" id="titleSelect">
    <form:option value="" label="Select title" />
    <form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />              
</form:select>
<form:errors path="title" cssClass="error"/>

<form:label path="firstName">First name:</form:label>
<form:input path="firstName"/>
<form:errors path="firstName" cssClass="error"/>

<form:label path="lastName">Last name:</form:label>
<form:input path="lastName"/>
<form:errors path="lastName" cssClass="error"/>

 <input type="submit" value="Submit" />
</form:form>

以防万一这是老师bean:

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "TEACHER_ID", unique = true, nullable = false)
private Integer teacherId;

@NotNull(message = "Teacher's first name is null!", groups = TeacherChecks.class)
@NotBlank(message = "Please enter teacher's first name!", groups = TeacherChecks.class)
@Column(name = "FIRST_NAME", nullable = false, length = 50)
private String firstName;

@NotNull(message = "Teacher's last name is null!", groups = TeacherChecks.class)
@NotBlank(message = "Please enter teacher's last name!", groups = TeacherChecks.class)
@Column(name = "LAST_NAME", nullable = false, length = 50)
private String lastName;

@NotNull(message = "Please choose title!", groups = TeacherChecks.class)
@Valid
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
@JoinColumn(name = "TITLE_FK", nullable = false)
private Title title;

@ManyToMany(mappedBy = "teachers")
private Set<Activity> activities;

public Teacher() {
}
// getters & setters

我想在页面重新加载后保留我选择的选项。我虽然会自动发生,就像我在文本字段中输入值一样,即使在页面重新加载后它仍然存在。有人可以帮我这个吗?有没有办法从控制器那里做到这一点,或者必须在视图中完成,以及如何做?

更新

我将value="${teacherAttribute.title}"添加到<form:select>,正如@willOEM建议的那样,但它仍然不起作用。现在它看起来像这样:

<form:select path="title" id="titleSelect" value="${teacherAttribute.title}">
    <form:option value="" label="Select title" />
    <form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />              
</form:select>

1 个答案:

答案 0 :(得分:3)

您的模型包含引用title类的属性Title。这与您在表单中引用的title不同,实际上是titleId。由于titleId不属于modelAttribute,因此应将其从<form:xxx>代码中排除。您将需要使用普通的<select>标记将选定的titleId传递回控制器进行处理。不幸的是,使用<select>标记时,您不能只使用JSTL设置value属性,因此您必须根据seelcted值有条件地设置选项的titleId属性(如果它已经设定)。如果titleListTitle个对象的简单列表,您可以通过以下方式创建<select>代码:

<select id="titleInput" name="titleId">
    <option value=""></option>
    <c:forEach items="${titleList}" var="title">
        <c:when test="${title.titleId== titleId}">
            <option value="${title.titleId}" selected>${title.titleName}</option>
        </c:when>
        <c:otherwise>
            <option value="${title.titleId}" >${title.titleName}</option>
        </c:otherwise>
    </c:forEach>
</select>

在您的控制器中,@RequestParam注释会从提交的数据中提取titleId。由于它不是modelAttribute的一部分,因此您需要确保将其添加为模型属性:

...
if (result.hasErrors()) {
    if (titleId != null) {
        model.addAttribute("titleId", titleId);  // <--This line added
        model.addAttribute("titleList", titleService.getAll());
        Title title = titleService.get(titleId);
        teacher.setTitle(title);
        model.addAttribute("teacher", teacher);
        return "addTeacher";
    }
    else {
        model.addAttribute("titleList", titleService.getAll());
        return "addTeacher";
    }
}
...

希望我们这次能得到它。