JSF 2 reusing the validation defined in the JPA entities?

若如初见. 提交于 2019-12-21 20:57:40

问题


Let's start with an example :


In my JPA entity

public class User {
    @Pattern("^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$", message="invalidEmailResourceBundleKey")
    private String email;

    @Min(5, message="minimumResourceBundleKey")
    private int age;

...
}

In my JSF Bean

public class UserBean {
    private User user;

    // do i have to redefine it here, since it's already a part of the user ?
    @@Pattern("^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$") 
    public String getEmail() {
        return user.getEmail();
    }
    public void setEmail(String s) {
        user.setEmail(s);
    }

    // do i have to redefine it here, since it's already a part of the user ?
    @Min(5, message="minimumResourceBundleKey")
    public int getAge() {
        return user.getAge();
    }
    public void setAge(int age) {
        user.setAge(age);
    }
}

Is it possible to reuse the the validations for the entities for the JSF beans that actually delegates the method calls to the entities, so that i dont have to redefine the bean validations on the JSF beans ?

Can i even extend the reusing to the level of the error message in resource bundle, and whether the message can be parameterized with {0} etc like the usual ? I wonder if there's any example on the web for this, since i've been unable to find none.

Please share your thoughts on this ..

Thank you !


回答1:


You don't need to redefine them if you don't unnecessarily flatten the bean properties. Just have a getUser() instead.

public class UserManager {

    private User user;

    public User getUser() {
        return user;
    }

}

And bind to the properties of the JPA entity directly.

<h:inputText value="#{userManager.user.email}" />
<h:inputText value="#{userManager.user.age}" />

Unrelated to the concrete problem, your email regex will fail for internationalized domain names (IDN) which are introduced last year. I'd fix the regex to not only accept latin characters. See also this answer for an example.



来源:https://stackoverflow.com/questions/5374009/jsf-2-reusing-the-validation-defined-in-the-jpa-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!