簡體   English   中英

Bean 驗證和 JAX-WS

[英]Bean Validation and JAX-WS

有沒有辦法讓 java bean 驗證 1.1 為 JAX-WS 工作? 我只看過適用於 JAX-RS 的文章。 我想要做的是能夠將驗證約束注釋添加到特定操作,並添加到整個 SOAP 消息或 SOAP 正文中,以執行使用規范化和 Schematron(而不是 XML 模式驗證)的自定義驗證。

JAX-WS 中的輸入驗證通常在 bean 實例化之前在 SOAP/XSD Schema/JAXB 級別上完成,這就是為什么您找不到展示如何一起使用這兩個東西的文章的原因。

此外,bean 驗證不能用於使用 XML/XPath 操作的 schematron 樣式驗證。

另一方面,Java bean 驗證是一種規范。 它是 Java EE 的一部分,可在 Java SE 中運行。 它可以與各種框架和庫一起使用,包括 JAX-WS 實現。 如果使用的框架本身不支持 bean 驗證,則可以手動觸發驗證過程。

因此,一般來說,可以在 JAX-WS 中使用 bean 驗證。 還可以實現各種自定義注釋以支持規范化。 同時,盡管在實現和處理上有相似之處,但我不會將規范化與驗證過程混為一談。

下面的代碼顯示了一些簡單的示例,盡管存在上下文/應用程序框架,但如何使用 bean 驗證。

1. 值對象必須被注解

public class Address {

    @Size(max = 100)
    private String City;

    @NotNull
    @Size(max = 200)
    private String Street;

    @Email
    private String email;

    @CountryCode
    private String countryCode;
}

2. 驗證過程可以手動觸發:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

Validator validator = factory.getValidator();

Set<ConstraintViolation<Address>> constraintViolations = validator.validate(address);

3. 可以實現自定義注釋以支持特定用例。

以下是用於驗證國家/地區代碼的注釋示例。 請注意,執行驗證的類包含在注釋代碼中,這在某些情況下是有意義的,以避免許多非常短的類。

@Documented
@Constraint(
        validatedBy = {CountryCode.CountryCodeValidator.class}
)
@Target({ElementType.METHOD,
        ElementType.FIELD,
        ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CountryCode {

    String message() default "Unknown Country code";

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

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

    /**
     * Validator implementation
     */
     class CountryCodeValidator implements ConstraintValidator<CountryCode, String> {

        private static final Set<String> ISO_COUNTRIES = 
                 new HashSet<String>(Arrays.asList(Locale.getISOCountries()));

        private CountryCode countryCodeAnnotation;

        @Override
        public void initialize(CountryCode countryCodeAnnotation) {
            this.countryCodeAnnotation = countryCodeAnnotation;
        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            if (s==null) {
                return true;
            }

            return ISO_COUNTRIES.contains(s);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM