イベントリスナーからマネージドBeanにアクセス - JSF

イベントリスナーからマネージドBeanにアクセスする– JSF

問題

JSFイベントリスナクラスは別のマネージドBeanにどのようにアクセスできますか? 以下のシナリオを参照してください。

JSFページ…


    
    

国が管理する豆…

package com.example;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="country")
@SessionScoped
public class CountryBean implements Serializable{

        private String localeCode;

    public void setLocaleCode(String localeCode) {
        this.localeCode = localeCode;
    }
    //...
}

ValueChangeListener…

package com.example;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

public class CountryValueListener implements ValueChangeListener{

    @Override
    public void processValueChange(ValueChangeEvent event)
            throws AbortProcessingException {

        //how to access the existing country managed bean?
        //country.setLocaleCode(event.getNewValue().toString());

    }

}

溶液

実際、イベントリスナクラスまたは別のマネージドBeanから既存のマネージドBeanにアクセスする方法は多数あります。 例を参照してください:

1. getApplicationMap()

国管理Beanがアプリケーションスコープで宣言されている場合。

    CountryBean country = (CountryBean) FacesContext.getCurrentInstance().
        getExternalContext().getApplicationMap().get("country");

2. getRequestMap()

国が管理するBeanが要求スコープで宣言されている場合。

    CountryBean country = (CountryBean) FacesContext.getCurrentInstance().
        getExternalContext().getRequestMap().get("country");

3. getSessionMap()

国管理Beanがセッションスコープで宣言されている場合。

    CountryBean country = (CountryBean) FacesContext.getCurrentInstance().
        getExternalContext().getSessionMap().get("country");

4. ELResolver()

ELResolverを使用します。

    FacesContext context = FacesContext.getCurrentInstance();
      CountryBean country = (CountryBean) context.
        getELContext().getELResolver().getValue(context.getELContext(), null,"country");

5. ValueExpression()

ValueExpressionを使用します。

    FacesContext context = FacesContext.getCurrentInstance();
      CountryBean country = (CountryBean) context.getApplication().getExpressionFactory()
            .createValueExpression(context.getELContext(), "#{country}", CountryBean.class)
              .getValue(context.getELContext());

6. evaluateExpressionGet()

evaluateExpressionGetを使用します。

    FacesContext context = FacesContext.getCurrentInstance();
      CountryBean country = (CountryBean)context.getApplication()
            .evaluateExpressionGet(context, "#{country}", CountryBean.class);