【问题标题】:Spring MVC: <form:select> option won't stay selectedSpring MVC:<form:select> 选项不会保持选中状态
【发布时间】:2014-01-29 16:31:20
【问题描述】:

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

这是控制器:

@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>

以防万一这是老师豆:

@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

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

更新

按照@willOEM 的建议,我将value="${teacherAttribute.title}" 添加到&lt;form:select&gt;,但它仍然不起作用。现在看起来像这样:

<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>

【问题讨论】:

    标签: spring-mvc select


    【解决方案1】:

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

    <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";
        }
    }
    ...
    

    希望这次我们能做到。

    【讨论】:

    • 感谢@willOEM 的回答。我在视图中添加了value="${teacherAttribute.title}",但它仍然不起作用:(我需要在控制器中更改什么吗?
    • @just_a_girl:请查看我的更新答案,有几项我在第一次通过时没有注意到。
    • 我无法删除 path 属性,因为它是必需的,我应该将其设置为 path="" 吗? @willOEM
    • 现在我收到错误 Required Integer parameter 'title' is not present :( @willOEM
    • 我的错误。由于titleId 不是modelAttribute 的一部分,我认为它不能成为&lt;form:xxx&gt; 标签的一部分。您可能只需要使用标准的 &lt;select&gt; 标记并使用 EL 来填充选项。我会尝试重新创建它并更新我的答案。
    猜你喜欢
    • 2017-12-25
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多