Java Spring3验证:在errorArgs中使用messages.property条目?

Java Spring3验证:在errorArgs中使用messages.property条目?,java,spring,localization,validation,locale,Java,Spring,Localization,Validation,Locale,我要找的很容易解释: 我有一个表格必须支持意大利语和英语。假设我有一个名字输入文本字段。表格标签将为: 对于EN:“名字” 为此:“诺姆” 我想要的是这样的验证错误消息 对于EN:“需要名字字段” 为此:“伊尔坎波Nomeèrichiesto” 请注意,我在错误消息中引用了字段名 我有消息\u en.properties和以下行: errors.empty.field = the {0} field is required registration.form.firstname = Fi

我要找的很容易解释: 我有一个表格必须支持意大利语和英语。假设我有一个名字输入文本字段。表格标签将为:

  • 对于EN:“名字”
  • 为此:“诺姆”
我想要的是这样的验证错误消息

  • 对于EN:“需要名字字段”
  • 为此:“伊尔坎波Nomeèrichiesto”
请注意,我在错误消息中引用了字段名

我有
消息\u en.properties
和以下行:

errors.empty.field = the {0} field is required
registration.form.firstname = First Name
errors.empty.field = il campo {0} è richiesto
registration.form.firstname = Nome
当然还有
消息\u it.properties
,带有以下行:

errors.empty.field = the {0} field is required
registration.form.firstname = First Name
errors.empty.field = il campo {0} è richiesto
registration.form.firstname = Nome
现在,在我的自定义验证器类中

ValidationUtils.rejectIfEmpty(errors, "firstname", "errors.empty.field", new Object[]{"registration.form.firstname"}, "the First Name is required");

它不能正常工作。输出是“registration.form.username”字符串。我希望在运行时将字段名注入适当的区域设置。有办法吗?

这是一种方法,但应该有更好的方法:

消息源
注入控制器或验证器:

@Autowired MessageSource messageSource
在controllers
@RequestMapping
方法中,将Locale作为参数,Spring将为您填充它

@RequestMapping(...)
public String myMethod(..., Locale locale){
   ValidationUtils.rejectIfEmpty(errors, "firstname", "errors.empty.field", new Object[]{messageSource.getMessage("registration.form.firstname", new Object[]{}, locale)}, "the First Name is required");
....
}
更新:


您可以使用

在验证器中获得
区域设置
的句柄,但我没有得到。我的CustomValidator类实现了org.springframework.validation.Validator格式的验证器。CustomValidator必须定义不允许区域设置参数的验证(对象目标、错误)。如何将locale对象传递给validator?我添加了一个更新,您可以使用
LocaleContextHolder.getLocale()
static调用。它确实感觉有点迂回,建议等待更多的答案,必须有一个更简单的方法来做。对不起,我想删除我愚蠢的问题…但我错过了你问题的轨迹…你能删除你的评论吗…实际上我在不知道消息来源的时候问了这个问题。。