我无法在JSP页面中显示验证错误消息。这是我的控制器:
@Controller
@RequestMapping("/secure")
@SuppressWarnings({"All"})
public class OperationController {
@ModelAttribute("crawler/operation")
public OperationForm operationForm() {
return new OperationForm();
}
@RequestMapping(value = "crawler/operation/create", method = RequestMethod.POST)
public String processCrawlerOperationForm(@Valid OperationForm operationForm, BindingResult result, Map model) {
if (result.hasErrors()) {
HashMap<String, String> errors = new HashMap<String, String>();
for (FieldError error : result.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
model.put("errors", errors);
return "crawler/operation";
}
//Some logic
return "crawler/operation";
}
}
我100%确定错误退出。我一直在调试此代码以确保存在错误。
我的表单类:
public class OperationForm {
@NotEmpty
private String operationName;
@NotEmpty
private String author;
@NotEmpty
private String configurationId;
public String getOperationName() {
return operationName;
}
//Getters and setters
}
我的JSP弹簧形式:
<form:form action="${pageContext.servletContext.contextPath}/secure/crawler/operation/create.htm" commandName="crawler/operation">
<table border="0" cellspacing="12">
<tr>
<td>
<spring:message code="application.operationForm.operationName"/>
</td>
<td>
<form:input path="operationName"/>
</td>
<td class="error">
<form:errors path="operationName"/>
</td>
</tr>
<tr>
<td>
<spring:message code="application.operationForm.author"/>
</td>
<td>
<form:input path="author"/>
</td>
<td class="error">
<form:errors path="author"/>
</td>
</tr>
<tr>
<td>
<spring:message code="application.operationForm.configuration"/>
</td>
<td>
<form:input path="configurationId"/>
</td>
<td class="error">
<form:errors path="configurationId"/>
</td>
</tr>
<tr>
<td>
<input class="button" type="submit" value="Vykdyti"/>
</td>
</tr>
</table>
</form:form>
我做错了什么?
答案 0 :(得分:2)
不是循环遍历错误列表并将它们插入到模型对象中,只需检查验证并返回视图,即
。if(result.hasErrors())
return "crawler/operation";
...
此外,在您的控制器方法中,添加@ModelAttribute注释,即
public String processCrawlerOperationForm(@ModelAttribute("form") @Valid OperationForm operationForm, BindingResult result, Map model)
当您最初显示表单时,确保ModelAttribute注释的值与您放入模型对象的值相匹配。如果您使用上面的方法operationForm来生成模型,请将其设置为该值的任何值。我将其更改为更有用的值,Spring可能会被/混淆,将其更改为简单的“形式”。