2014-11-01 65 views
1

我想弄清楚我在開發小型應用程序時遇到的一個小問題的解決方案。我試圖傳遞在一個支持bean內創建的對象,然後使用在另一個支持bean內創建的相同對象。但是,我不想製作這些備用豆@SessionScoped,並且最好不要使用@ManagedBean,因爲我正在爲我的JavaEE應用程序使用CDIJSF:將一個對象從一個支持bean傳遞到另一個支持bean

有無論如何,我可以做到這一點使用CDI批註和注入一個支持豆到另一個,然後有能力訪問先前創建的對象?

作爲一個例子,請參考下面豆:上述豆內創建

@Named 
@ViewScoped 
public RegisterController implements Serializable { 

    User user = new User(); 

    // Getter and Setter methods which are populated by the JSF page 
} 

獲取對象User和下面的控制器內使用它:

@Named 
@ViewScoped 
public PaymentController implements Serializable { 

    @Inject RegisterController registerController; // Injecting bean 

    registerController.getUser().getName(); //this is null when I try access the properties of the object 'User'. I am assuming this is because @ViewScoped annotated on the 'RegisterController' class? 

    // I would like to use the User object created in 'RegisterController' here an access properties etc... 
} 

我可以使用@Inject註解由CDI提供?

UPDATE

好了,我已經得到了上面的工作,當我註釋RegisterControllerSessionScoped註釋,但我不希望這個bean註釋SessionScoped,我可能會遇到在軌道下進一步影響,比如字段的預填充等等......任何想法如何以任何其他方式實現這一點?

+0

@SalihErikci,'@ RequestScoped' CDI註解不起作用,因爲Object必須持續更長的時間,然後再持續一個'HTTP Request'。 – Maff 2014-11-01 12:46:20

回答

2

那麼,@ViewScoped太短,@SessionScoped太長。那麼爲什麼不使用@ConversationScoped

請參閱here

+0

我已經使用CDI @ConversationScoped實現了這個功能。謝謝你的提示。 – Maff 2014-11-02 10:34:13

0

,你可以在這個RegistrationController使用:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user); 

和PaymentController:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user"); 

這是非常有用的,可以節省你在地圖上想要的對象。

相關問題