Spring 3验证:在errorArgs中使用messages.property条目?

MaV*_*ldo 5 java validation spring locale localization

我正在寻找的东西很容易解释:我有一个必须支持意大利语和英语的表格.假设我有一个名字输入文本字段.表格标签将是:

  • EN:"名字"
  • 对于IT:"Nome"

我想要的是这样的验证错误消息

  • 对于EN:" 需要名字字段"
  • 对于IT:"坎普广场诺姆 èrichiesto"

请注意我在错误消息中引用了字段名称.

messages_en.properties有线:

errors.empty.field = the {0} field is required
registration.form.firstname = First Name
Run Code Online (Sandbox Code Playgroud)

当然还有messages_it.properties线条:

errors.empty.field = il campo {0} è richiesto
registration.form.firstname = Nome
Run Code Online (Sandbox Code Playgroud)

现在,在我的自定义验证器类中

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

这不能正常工作.输出是"registration.form.username"字符串.我想在运行时使用适当的语言环境注入字段名称.有办法吗?

Bij*_*men 2

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

将 注入messageSource到控制器或验证器中:

@Autowired MessageSource messageSource
Run Code Online (Sandbox Code Playgroud)

在您的控制器@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");
....
}
Run Code Online (Sandbox Code Playgroud)

更新:

Locale您可以使用LocaleContextHolder在 Validator 中获取句柄