提前感谢您的帮助。
我有一个正在使用JSR 303验证的表单。验证失败后,控制器返回表单,显示验证错误,并使用原始值呈现表单。除了mutli-select元素之外,这适用于所有类型的表单元素。
命令对象:
public class TaskOrder implements Serializable {
private static final long serialVersionUID = 1L;
...
@XmlTransient
@ManyToMany
@<OtherJPAAnnotations...>
private List<Contractor> subcontractors;
...
}
承包商类:
public class Contractor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@<OtherJPAAnnotations...>
private Integer id;
@<OtherJPAAnnotations...>
private String name;
}
控制器:
@RequestMapping(value="processingPath", method=RequestMethod.POST)
public String createNewTaskOrder(@Valid @ModelAttribute TaskOrder taskOrder,
BindingResult result,
Model model) {
...
if (!result.hasErrors()) {
//No binding errors, lots of processing...
else {
model.addAllAttributes(result.getModel());
model.addAttribute(taskOrder);
model.addAttribute("subs", myDAOInstance.getSubs());
return this.setupNewTaskOrder(model);
}
}
@RequestMapping("getFormPath")
public String setupNewTaskOrder(Model model) {
if (!model.containsAttribute("taskOrder")) {
TaskOrder taskOrder = new TaskOrder();
taskOrder.setId(0);
model.addAttribute(taskOrder);
}
return "_n/admin/taskOrder/new";
}
表格:
<form:form commandName="taskOrder" action="processPath">
...
<form:select path="subcontractors">
<form:options items="${subs}" itemValue="id" itemLabel="name"/>
</form:select>
...
</form>
当我打开具有相同形式的现有“TaskOrder”时,将在“subcontractors”multi-select中选择值。
但是,尝试添加新的“TaskOrder”,当它从验证返回时,不会选择值。我知道所选的值正在附加到模型并返回,但只是没有在select元素中被选中。
感谢您的帮助!
答案 0 :(得分:0)
感谢您的帮助。比居......你说的没错!
对于那些可能偶然发现此问题的人,我将此处描述的“EqualsUtil”类添加到我的项目中: http://www.javapractices.com/topic/TopicAction.do?Id=17
然后将以下方法添加到我的Contractor类:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Contractor)) return false;
Contractor c = (Contractor) o;
//Here I ignore the other properties since "id" and "name" are what
//I'm primarily concerned with...
return EqualsUtil.areEqual(this.name, c.name) &&
EqualsUtil.areEqual(this.id, c.id);
}