2012-07-27 34 views
1

我有许多使用相同验证约束的jsf2 web项目。共享库中的Bean验证约束条件

  1. 我可以将所有这些约束放在共享库中吗?
  2. 如果是,我可以提供验证消息的转换吗?
  3. 如果是的话,我怎样才能以标准的方式实现它?
  4. 以下包装结构是否正确?

commons.jar库:

commons.jar 
    | 
    + library 
    | | 
    | + CustomConstraint1.class 
    | + CustomConstraint2.class 
    | 
    + ValidationMessages_it.properties 
    + ValidationMessages_en.properties 
    + ValidationMessages_de.properties 

回答

1

你的捆绑是正确的一个独立的罐子。如果您将此jar放入ear/war中,并且它自己的约束和classpath根目录中的ValidationMessages.properties,它将不起作用。

+0

如果您使用Hibernate 5。2或更高版本,可以通过在http://stackoverflow.com/a/33442715/1108305上按我的回答配置PlatformResourceBundleLocator来解决重复资源问题 – 2015-10-30 18:37:04

2
  1. 我可以把所有这些限制在一个共享库?

是的,你可以。

  1. 如果是,我可以提供验证消息的转换吗?

是的,这也是可能的。

  1. 如果是,我该如何以标准方式实现它?

例如,你有这样的约束:

package com.example.constraints; 

@Target({ 
     ElementType.FIELD, 
     ElementType.PARAMETER, 
     ElementType.METHOD 
}) 
@Retention(RetentionPolicy.RUNTIME) 
@Constraint(validatedBy = { 
    FooValidator.class 
}) 
public @interface Foo 
{ 
    String message() default "{com.example.constraints.Foo.message}"; 

    Class<?>[] groups() default {}; 

    Class<? extends Payload>[] payload() default {}; 
} 

指定类路径的根目录(应用程序的默认语言)一ValidationMessages.properties。对于额外的语言环境,您应该指定一个ValidationMessages_[locale].properties文件。对于荷兰语区域,它应该是ValidationMessages_nl.properties

然后在这些文件中定义你的消息变量作为密钥和消息作为这样一个值:

com.example.constraints.Foo.message=Foo is not valid 
+0

您好siebz0r,谢谢您的回复。你可以看看我的问题中的新观点并更新你的答案吗?再次感谢您 – Alf 2012-07-27 12:32:08

+0

包装结构似乎正确。 – siebz0r 2012-07-27 13:55:09

+0

这是一个好消息,但不幸的是它不适合我。如果我把这个库放在一个web应用程序中,{{com.example.constraints.Foo.message} _显示为消息。如果我在另一个位置有一个带有消息键的复合约束,它会有点工作,但如果我在Web-INF/classes文件夹中添加一个ValidationMessages_it.properties(例如),它将停止工作。请参阅http://stackoverflow.com/questions/11599208/multiple-validationmessages-properties – Alf 2012-07-27 14:09:31