首页 文章

在验证期间未使用Spring MessageSource

提问于
浏览
3

我无法在messages.properties中获取我的消息,以便在我的表单支持对象的Spring验证期间使用 .

APP-config.xml文件:

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

WEB-INF /班/ messages.properties:

NotEmpty=This field should not be empty.

表格支持对象:

...
  @NotEmpty
  @Size(min=6, max=25)
  private String password;
...

当我遍历BindingResult中的所有错误并输出ObjectError的toString时,我得到:

Field error in object 'settingsForm' on field 'password': rejected value []; codes [NotEmpty.settingsForm.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [settingsForm.password,password]; arguments []; default message [password]]; default message [may not be empty]

正如您所看到的,默认消息是“可能不为空”而不是我的消息“此字段不应为空” .

如果我将messageSource注入控制器并输出它,我会得到正确的消息:messageSource.getMessage(“NotEmpty”,new Object [] {“password”},“default empty message”,null);

那么为什么不使用我的messages.properties进行验证呢?我正在运行Spring 3.1.1 . 谢谢!

3 回答

  • 1

    @NotEmpty有一个可以在其上设置的消息属性 . 由于您没有设置它,它使用默认消息 .

    @NotEmpty(message="{NotEmpty}")
    

    应该给你你想要的东西 .

  • 7

    默认情况下,HibernateValidator将从 /WEB-INF/classes/ValidationMessages.properties 获取所有消息 . 它直接读取此文件,而不是通过Spring MessageSource .

    如果您想要从Spring消息源进行翻译,请在LocalValidatorFactoryBean上设置一个 . 这确实需要您在调度程序servlet中手动设置验证bean,而不是依赖于mvc:annotation-driven .

  • 2

    如果要使用JSR 303验证为任何字段设置自定义消息,则需要在属性文件中的消息键中指定bean名称(LoginForm)和字段名称(密码) . 格式为CONSTRAINT_NAME.COMMAND_NAME.FIELD_NAME

    NotEmpty.loginform.password=This field should not be empty.
    

相关问题