【问题标题】:Using ValidationMessages bundle with Spring Webflow Validation?将 ValidationMessages 捆绑与 Spring Webflow 验证一起使用?
【发布时间】:2023-04-09 20:53:01
【问题描述】:

如何在自定义 Webflow Validator 类中连接 Spring ValidationMessages 包?我已经实现并运行了一个验证器:

public void validateBusinessReferences(BusinessReferencesViewDao businessReferences, Errors errors) {
    if (somecondition())) {
        errors.rejectValue("name", "validation.message123", "This field is bad.");
    }
}

但我得到的不是来自 ValidationMessages.properties 文件的消息,而是 This field is bad. 的回退默认值

我的所有其他消息和验证都可以正常工作 - 只是这个自定义验证器/自定义消息场景失败了。我怀疑某种 Spring 配置问题,但我无法隔离它。

【问题讨论】:

    标签: java spring spring-webflow-2


    【解决方案1】:

    我的理解是ValidationMessages.properties 是用于在使用 JSR-303 样式注释时自定义消息。由于您在这里没有使用那些 - 而是使用自定义验证器方法并直接调用 errors.rejectValue,因此您应该将消息放在标准的 messages.properties 文件中。在 webflow 中,此文件是特定于流的,并且与流定义 XML 文件一起位于同一文件夹中。

    【讨论】:

    • 是的,我尝试了几种不同的方法。我终于用 MessageResolver 把它理顺了。 Spring 文档对于哪些消息文件对于这些消息是“正确的”这一点不是很清楚,它们可能都可以放入其中。我最终将它们都放在了我的消息源 bean 中,并且还添加了实际调用 resolveMessage() 的重要步骤,它根据消息源解析消息。我以前没有那样做。 (糟糕。)
    【解决方案2】:

    问题已解决 - 我错过了一步。为了使用属性包,您需要使用 MessageResolver 并像这样调用它:

    MessageResolver messageResolver = new MessageBuilder().error().source(source).code("validation.message.property.here").defaultText(errorMessage).build();
    messageResolver.resolveMessage(messageSource, Locale.ENGLISH);
    return messageResolver;
    

    您的 messageSource 是带有消息属性包的 Spring bean,在您的应用程序上下文中定义:

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>messages</value>
                <value>ValidationMessages</value>
            </list>
        </property>
    </bean>
    

    MessageResolver 的文档是 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-06
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多