在验证期间未使用Spring MessageSource

时间:2012-06-20 21:15:12

标签: java spring hibernate validation spring-mvc

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

应用-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 个答案:

答案 0 :(得分:7)

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

如果您想要来自Spring Message source的翻译,请在LocalValidatorFactoryBean上设置一个。这确实需要您在调度程序servlet中手动设置验证bean,而不是依赖于mvc:annotation-driven。

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

@NotEmpty(message="{NotEmpty}")

应该给你你想要的东西。