Spring MVC:< form:select>选项不会保持选中状态 [英] Spring MVC: <form:select> option won't stay selected

查看:96
本文介绍了Spring MVC:< form:select>选项不会保持选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple form for adding a new teacher. I'm using Spring <form:select> in my view to show a list of teacher's titles, but when I select an option without entering teacher's first and/or last name, since I'm doing validation of all three fields, when the page loads after submit, previously selected option gets lost and "Select title" text appears again.

这是控制者:

@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

页面重新加载后,我想保留我选择的选项.尽管它会自动发生,例如当我在文本字段中输入值时,即使在页面重新加载后,它也会停留在该位置.有人可以帮我吗?有没有一种方法可以从控制器执行此操作,或者必须在视图中完成,以及如何执行?

I would like to keep my selected option after page reloads. I though it will happen automatically, like when I enter a value into a text field, it stays there even after the page reloads. Can someone please help me with this? Is there a way to do that from the controller, or it has to be done in the view, and how?

更新:

按照@willOEM的建议,我在<form:select>中添加了value="${teacherAttribute.title}",但仍然无法正常工作.现在看起来像这样:

I added value="${teacherAttribute.title}" to <form:select>, as @willOEM suggested, but it still doesn't work. Now it looks like this:

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

推荐答案

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

Your model includes an attribute title that refers to a Title class. This is not the same title you are referring to in your form, which is actually a titleId. Since the titleId is not part of the modelAttribute, it should be excluded from the <form:xxx> tags. You are going to need to use a plain-old <select> tag to pass the selected titleId back to the controller for processing. Unfortunately with a <select> tag, you can't just set the value attribute with JSTL, so you have to conditionally set the seelcted attribute of the option, based on the titleId value (if it is set). If titleList is a simple list of Title objects, you can create your <select> tag this way:

<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的一部分,因此需要确保将其添加为模型属性:

In your controller, the @RequestParam annotation will pull the titleId out of the submitted data. Since it is not part of the modelAttribute, you need to make sure this gets added as a model attribute:

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

希望我们这次得到了.

这篇关于Spring MVC:&lt; form:select&gt;选项不会保持选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆