2013-02-08 65 views
1

有沒有辦法從Validator設置bean屬性?
在我的情況下,我有一個validator連接到數據庫並執行一些驗證。
成功驗證後,我想將從數據庫收到的對象保存在bean屬性中。
目前我通過從驗證器設置我的bean的靜態屬性來做到這一點。
這裏是我的驗證方法從驗證器設置bean屬性

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); 
    } 
} 

,這裏是我的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 
} 

所以在我腦海中的問題是:

  • 有沒有辦法直接設置bean屬性從豆? (沒有 使用靜態屬性)
  • 會有任何併發​​性問題(一個用戶可能會接收其他用戶選擇的引用對象等)使用現有的方法嗎?

謝謝管理豆

+1

在管理豆靜態成員的所有實例(和你的應用程序的用戶)之間共享的託管bean。所以在使一個成員變量靜態之前至少考慮兩次。 –

+0

感謝@MattHandy的回覆。 那麼如何在不使用靜態屬性的情況下從驗證器設置bean屬性? –

+1

如果你讓你的驗證器成爲一個託管bean,你可以將你的目標託管bean注入驗證器。有關詳細信息,請參閱[此答案](http://stackoverflow.com/a/8629655/620338)。 (在這個例子中,注入了一個EJB,但是可以通過'@ ManagedProperty'註釋來注入一個JSF託管bean)。 –

回答

3

靜態成員的所有實例(和你的應用程序的用戶)之間共享。所以在使一個成員變量靜態之前至少考慮兩次。

如果你讓你的驗證器成爲一個託管bean,你可以將你的目標託管bean注入到驗證器中。詳情請參閱this answer

在給出的示例的EJB注入,但你可以注入一個JSF通過@ManagedProperty註釋

+0

回答接受! :) –

相關問題