0

我正在尝试为我的 Spring 表单运行一个验证器类,但我的错误没有显示在我的页面上。我是 Spring 验证的新手,所以这里无疑存在一些错误。这是我的表格。(顺便说一句,Eclipse 会在以下行中发布警告form:error:“List 是原始类型。对泛型类型 List 的引用应该被参数化。”)

<form:form commandName="bulletin" method="post" action="processBulletin">
    <table>
        <tr>
            <td>Name:</td>
            <td><form:errors path="name" /></td>
            <td><form:input path="name" maxlength="30" /></td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td><form:errors path="subject" /></td>
            <td><form:input path="subject" maxlength="50" /></td>
        </tr>
        <tr>
            <td valign="top">Message:</td>
            <td><form:errors path="note" /></td>
            <td><form:textarea path="note" cols="70" rows="20" /></td>
        </tr>
        <tr>
            <td><input type="submit" /></td>
            <td>&nbsp;</td>
        </tr>
    </table>
</form:form>

这是我的控制器类。我从这里调用验证类,我不确定这是否是正确的做法,所以如果不是,请随意说。

@RequestMapping(value = "/processBulletin", method = RequestMethod.POST)
public String processBulletin(
        @ModelAttribute("bulletin") Bulletin bulletin, BindingResult result) {
    final BindException errors = new BindException(bulletin, "bulletin");

    bulletinValidator.validate(bulletin, errors);
    if (errors.hasErrors()) {
        return "redirect:/approvedBulletins";
    } else {
        // rest of method
    }

    return "redirect:/approvedBulletins";
}

这是我的验证课。

    @Override
    public boolean supports(Class<?> cls) {
        return Bulletin.class.isAssignableFrom(cls);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subject", "Subject is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "Name is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "note", "Message is required");
    }
}
4

1 回答 1

0

当您遇到错误时,请尝试返回view name而不是重定向。return "redirect:/approvedBulletins";

于 2013-04-18T05:28:30.317 回答