2012-04-03 88 views
0

我确认两种方式 - 用spring验证自定义验证和javax.validation快速和一般javax.validation如何定位不同的语言环境?

春做事规规矩矩,其中该代码会正好与给定语言环境来记录和所需的文本中提取。

private Errors checkPasswordMatch(Person p, Errors errors) { 
    if (!p.getPassword().equals(p.getRepeatedPassword())) { 
    errors.rejectValue("password", "person.password.mismatch"); 
    errors.rejectValue("repeatedPassword", "person.password.mismatch"); 
    } 
    return errors; 
} 

Javax不那么麻烦,但没有办法用不同的语言生成消息。

@NotNull 
    @Size(min = 10, max = 10, message = "size must be 10 characters") 
    protected String birthDate; 

如何建议的javax去一些GB.properties或US.properties或IT.properties文件中提取相同的双向弹簧并根据用户的语言环境的消息?

回答

5
@Size(min = 10, max = 10, message = "{birthDate.size}") 
protected String birthDate; 

在(创建一个在类路径中,如果你没有一个)ValidationMessages.properties定义为birthDate.size = some message

编辑1:

保持单独的文件。不同于应用程序特定的消息,ValidationMessages需要随时随同豆一起发货/打包。您不需要为ValidationMessages.properties文件定义一个bean。它会被自动提取

+0

正确:详细信息可以在“bean validation 1.0 final spec”(http://download.oracle.com/otndocs/jcp/bean_validation-1.0- fr-oth-JSpec /) – Ralph 2012-04-03 09:11:52

+0

如何合并两个文件?因为我使用\t <豆ID = “为messageSource” 类= “org.springframework.context.support.ReloadableResourceBundleMessageSource”> \t \t \t <属性名= “基名” 值= “/ WEB-INF /消息”/> \t \t \t \t已经,这些会给我两套文件? – Aubergine 2012-04-03 09:50:28

+0

见上文edit1 – fmucar 2012-04-03 10:06:44

0

我不知道javax.validation那么好,但是我认为你会在ValidationException中得到这条消息。

因此,为异常而不是消息定义消息键,并且在显示异常/消息时自己在相应的资源包中进行查找。

在Struts2的,我们会做这样的事:

@Size(min = 10, max = 10, message = "size.exact.10") 
    protected String birthDate; 

    //in the JSP display the message: 
    <s:text name="%{exception.message}"/> 

我想你可以做同样的事情。