S1LENT WARRIOR
S1LENT WARRIOR

Reputation: 12204

Setting bean property from validator

Is there a way to set a bean property from a Validator?
In my case, I have a validator which connects to the database and performs some validation.
Upon successful validation, I want to save the object received from database, inside a bean property.
Currently i'm doing this by setting a static property of my bean from the validator.
Here is my validator method

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    //perform validation
    if(isValidated) {
        Referral ref = database.getReferral(value.toString());  //receive referral object from batabase
        RegistrationBean.staticReferral = ref; // Set ref to RegistrationBean's static property
    } else {
       FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Invalid Referral!", "Referral does not exist!");
        throw new ValidatorException(msg);
    }
}  

and here is my RegistrationBean

@ManagedBean  
@ViewScoped  
public class RegistrationBean implements Serializable {

    //other bean properties
    private Referral referral;
    public static Referral staticReferral;

    public RegistrationBean() {
        //default constructor
    }

    public Referral getReferral() {
        this.staticReferral = referral;
        return referral;
    }
    // other getters, setters and methods
}

So the questions in my mind are:

Thanks

Upvotes: 1

Views: 275

Answers (1)

Matt Handy
Matt Handy

Reputation: 30025

Static members in managed beans are shared among all instances (and users of your application). So think at least twice before making a member variable static.

If you make your validator a managed bean, you can inject your target managed bean into your validator. See this answer for details.

In the given example an EJB is injected, but you can inject a JSF managed bean via the @ManagedProperty annotation

Upvotes: 3

Related Questions