วันเสาร์ที่ 7 พฤษภาคม พ.ศ. 2559

Bean Validation

Bean Validation



-มีการทำงานร่วมกับ CDI, JAX-RS, JPA, JSF และอื่นๆ ประกอบด้วย CDI, Method validation, มีการใช้งานร่วมกับ JAX-RS (REST Service) และการสร้าง Error messages โดยใช้ EL expressions

-CDI Alignment
ประกอบด้วย Delegate Bean Validation component lifecycle มีประโยชน์อย่างยิ่งในการปรับปรุง ConstraintValidator

public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
    @Inject @France private ZipCodeChecker checker;
    public void initialize(ZipCode zipCode) {}
    public boolean isValid(String value, ConstraintValidationContext context) {
        if (value==null) return true;
        return checker.isZipCodeValid(zipCode); 
    }
}

-ตัวอย่าง Method Validation

@RequestScope public class Client {
    @Inject AccountService service;
    public void createClient() { service.createUser(...); }
}

@ApplicationScoped public class AccountService {       @NotNull public User createUser(             @NotEmpty String username,             String firstname, String lastname,             @Valid Address home,             @NotNull @Email String email,             @Past Date birthDate) {         // parameters are validated and an exception         // is raised upon failure         // business     } }

-การใช้งานร่วมกับ JAX-RS
โดยใช้ Bean Validation constraints ด้วย method validation

@Path(“/user”)
public class UserResource {
    @Post
    @Consumes("application/x-www-form-urlencoded")
    public void register(
        @NotEmpty @FormParam(“firstname”) String firstname,
        @NotEmpty @FormParam(“lastname”) String lastname,
        @NotNull @Email @FormParam(“email”) String email) { ... }

    // Works on fields and getters too }

การสร้าง Error messages โดยใช้ Expression Language
-การเพิ่มความสามารถในการใช้ EL เพื่อตรวจสอบข้อความผิดพลาด
-การเข้าถึงพารามิเตอร์ ข้อจำกัด และการสร้างความคุ้มค่า
-การเพิ่มข้อเสนอที่มีการแปล กรณีการจัดรูปแบบสตริงที่เกินไป

javax.validation.constraints.DecimalMax.message=\
    must be less than ${inclusive == true ? 'or equal to ' : ''}{value}

Resources
-Bean Validation project page
http://beanvalidation.org
-Glassfish 4
https://glassfish.java.net/

Reference : เอกสาร What’s New with Bean Validation in Java EE 7 โดย Reza Rahman (Java EE/GlassFish Evangelist) จาก Oracle ในงาน JavaOne

ไม่มีความคิดเห็น:

แสดงความคิดเห็น