我有以下JSP类
<form:form method="POST" modelAttribute="task">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="reference">Reference: </label> </td>
<td><form:input path="reference" id="reference"/></td>
<td><form:errors path="reference" cssClass="error"/></td>
</tr>
<tr>
<td><label for="cause">Cause: </label> </td>
<td><form:input path="cause" id="cause"/></td>
<td><form:errors path="cause" cssClass="error"/></td>
</tr>
<tr>
<td><label for="offense">Offense: </label> </td>
<td><form:select path="offense.id" items="${offenses}" required="true" itemLabel="offense" itemValue="id"/> </td>
<td><form:errors path="offense" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update"/>
</c:when>
<c:otherwise>
<input type="submit" value="Register"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
并且控制器方法看起来像这样
@RequestMapping(value = {"/new"}, method = RequestMethod.GET)
public String newTask(ModelMap model) {
Task task = new Task();
List<Offense> offenses = offenseService.findAllOffenses();
model.addAttribute("task", task);
model.addAttribute("edit", false);
model.addAttribute("offenses", offenses);
return "registration";
}
@RequestMapping(value = {"/new"}, method = RequestMethod.POST)
public String saveEmployee(@Valid Task task, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if (!taskService.isTaskUniqueReference(task.getReference())) {
FieldError referenceError = new FieldError("Task", "reference", messageSource.getMessage("non.unique.reference", new String[]{String.valueOf(task.getReference())}, Locale.getDefault()));
result.addError(referenceError);
return "registration";
}
taskService.saveTask(task);
model.addAttribute("success", "Task " + task.getReference() + " registered successfully");
return "success";
}
问题是,当我点击提交并触发错误时,例如重复的参考字段,错误会在参考字段的左侧正确显示,但下拉菜单中的选项会消失,为什么是初始模型图数据丢失了?我怎么能解决这个问题,我试图在hasErrors()的情况下将攻击添加到模型图中,但没有解决问题。
答案 0 :(得分:0)
试试这个:
List<Offense> offenses = offenseService.findAllOffenses();
if (!taskService.isTaskUniqueReference(task.getReference())) {
FieldError referenceError = new FieldError("Task", "reference",
messageSource.getMessage("non.unique.reference",
new String[] { String.valueOf(task.getReference()) }, Locale.getDefault()));
result.addError(referenceError);
model.addAttribute("offenses", offenses);
return "registration";
}