【问题标题】:Spring 3 form validation shows error messages but field name not displayedSpring 3 表单验证显示错误消息但未显示字段名称
【发布时间】:2013-04-19 13:03:36
【问题描述】:

我有一个 2 项表单,需要输入两个字段。我正在使用带注释的验证,并且收到错误消息,但它们不打印字段名称,只是“可能不是空白”而不是“一个可能不是空白”,其中一个是字段名称。

有什么想法吗?这是一个非常简单的例子:

@Controller
@SessionAttributes
 public class HomeController
{

private static final Logger logger  = LoggerFactory
                                            .getLogger(HomeController.class);

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
    logger.info("Welcome home! The client locale is {}.", locale);
    model.addAttribute("homeformitem", new HomeFormItem());
    return "home";
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public String home(
        @ModelAttribute("homeformitem") @Valid HomeFormItem item,
        BindingResult result)
{
    logger.info("Posting form");
    logger.info(item.toString());
    if (result.hasErrors())
    {
        return "home";
    } else
    {
        logger.info("No Errors");
        return "done";
    }
}
}

这是表格。我收到错误消息,但没有收到字段名称。

表单验证!

    <f:form method="post" modelAttribute="homeformitem">
    <fieldset>
        <legend>Fields</legend> 
    <table>
        <tr><td colspan="3"><f:errors path="*"/></td></tr>
        <tr>
            <td><f:label path="one" for="one">One: </f:label></td>
            <td><f:input path="one" /></td>
            <td><f:errors path="one" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td><f:label path="two" for="two">Two: </f:label></td>
            <td><f:input path="two" /></td>
            <td><f:errors path="two" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td colspan="3"><input type="submit" value="Test" /></td>
        </tr>
    </table>
</fieldset>
</f:form>

【问题讨论】:

标签: forms spring validation annotations field-names


【解决方案1】:

您需要一个位于/WEB-INF/messagesvalidation.properties 文件,其中包含与此类似的条目(例如):

NotEmpty.homeFormItem.one=The field {0} is empty

别忘了添加一个 spring bean 来解析您的验证消息:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages/validation" />
</bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-11
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多