MaV*_*ldo 5 java validation spring locale localization
我正在寻找的东西很容易解释:我有一个必须支持意大利语和英语的表格.假设我有一个名字输入文本字段.表格标签将是:
我想要的是这样的验证错误消息
请注意我在错误消息中引用了字段名称.
我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"字符串.我想在运行时使用适当的语言环境注入字段名称.有办法吗?
这是一种方法,但应该有更好的方法:
将 注入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 中获取句柄
归档时间: |
|
查看次数: |
1294 次 |
最近记录: |