【问题标题】:Spring-mvc validation error not being picked from property file未从属性文件中选择 Spring-mvc 验证错误
【发布时间】:2014-02-02 08:38:27
【问题描述】:

在 JSR303 bean 验证中使用 spring-mvc 构建,它工作正常,除了一个问题,没有从属性文件中选择消息。

我的 Web 应用程序是用 maven 创建的,这是当前结构

Main
      -java
      -resources
         -bundles
            -message.properties
      -webapp

XML 文件

<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <beans:property name="basenames">
    <beans:list>
    <beans:value>bundles/messages</beans:value>
    <beans:value>bundles/shipping</beans:value>
    <beans:value>bundles/payment</beans:value> 
     </beans:list>
  </beans:property>
 </beans:bean>

-- 验证器

<beans:bean id="validator"   
   class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  <beans:property name="validationMessageSource" ref="messageSource"/>
</beans:bean>

注释驱动

<annotation-driven>
  <message-converters>
            <beans:bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
                <beans:property name="supportedMediaTypes">
                    <beans:list>
                        <beans:value>image/jpeg</beans:value>
                        <beans:value>image/gif</beans:value>
                        <beans:value>image/png</beans:value>
                    </beans:list>
                </beans:property>
            </beans:bean>
        </message-converters>
</annotation-driven>

Java 文件

@NotEmpty(message="{registration.firstName.invalid}")
  public String getFirstName() {
   return firstName;
}

在我的 JSP 页面上,我收到了这些消息 This field is required,不确定是什么问题 我的数据类具有以下结构

PersistableCustomer extends SecuredCustomer
SecuredCustomer extends CustomerEntity

即使在将消息源传递给验证器之后,它也不会从自定义属性文件中获取消息。

【问题讨论】:

  • 您的messageS.properties 名称中缺少s。但我认为这只是问题中的一个错字,对吧?
  • @PavelHoral: 这是一个错字:)
  • 看看this answer,也是一样的情况。
  • @JakubJirutka:我没有使用任何自定义验证器,仅使用开箱即用提供的验证
  • @UmeshAwasthi 无关紧要,关键是您使用的是非默认消息源。相信我,试试我的解决方案,它会起作用的。 ;)

标签: spring spring-mvc bean-validation


【解决方案1】:

我在这里猜测一下...通常 JSR-303 消息插值器从 ValidationMessages.properties 获取消息。如果你想让你的验证器使用 Spring 的消息源,你需要这样配置:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource" />
</bean>

<mvc:annotation-driven validator="validator" />

【讨论】:

  • 这没有帮助..即使按照建议进行设置..它仍然选择默认值
  • 您的 MVC 基础架构是如何定义的?你只是使用&lt;mvc:annotation-driven /&gt; 还是有一些更细粒度的配置?你可能需要用你的验证器定义 web binding initializerdocs.spring.io/spring/docs/3.1.4.RELEASE/javadoc-api/org/…
  • 我正在使用&lt;mvc:annotation-driven /&gt;,更新我的帖子所需的详细信息。请看一下
  • 更新了我的答案...您可以在&lt;mvc:annotation-driven&gt; 元素上设置validator 引用。
  • 我仍然面临着奇怪的问题..虽然绑定结果显示正确的错误但仍然在 jsp 上显示相同的默认消息&lt;form:errors path="firstName" cssClass="error" /&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 2022-07-29
  • 1970-01-01
  • 2015-11-24
相关资源
最近更新 更多