1

我无法在 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>

我究竟做错了什么?

4

1 回答 1

2

而不是遍历错误列表并将它们插入模型对象,只需检查验证并返回视图,即

if(result.hasErrors())
  return "crawler/operation";
...

此外,在您的控制器方法中,添加 @ModelAttribute 注释,即

public String processCrawlerOperationForm(@ModelAttribute("form") @Valid OperationForm operationForm, BindingResult result, Map model)

确保 ModelAttribute 注释的值与您在最初显示表单时放入模型对象的值相匹配。如果您使用上面的方法 operationForm 生成模型,请将其设置为该值。我会将其更改为更有用的值,Spring 可能会被 / 弄糊涂,将其更改为像“form”这样简单的东西。

于 2012-05-31T17:31:11.933 回答