我正在尝试使用javax.faces.event.ValueChangeListener
对h:selectOneMenu
这样的
<h:selectOneMenu value="#{localeBean.languageCode}" onchange="submit()">
<f:selectItem itemLabel="English" itemValue="en" />
<f:selectItem itemLabel="German" itemValue="de" />
<f:valueChangeListener type="org.bitbucket.paulstat.jsf.event.ExampleValueChangeListener" />
</h:selectOneMenu>
这是听众
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
import javax.inject.Inject;
import org.bitbucket.paulstat.jsf.localisation.LocaleBean;
public class ExampleValueChangeListener implements ValueChangeListener {
@Inject
private LocaleBean localeBean;
@Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
localeBean.setLanguageCode(event.getNewValue().toString());
localeBean.switchLocale();
}
}
LocaleBean
import java.io.Serializable;
import java.util.Locale;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
@Named
@SessionScoped
public class LocaleBean implements Serializable {
private String languageCode;
public void switchLocale() {
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(languageCode));
}
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
public String getLanguageCode() {
return languageCode;
}
}
LocaleBean
似乎没有被注入值更改侦听器并且为null。我们可以将SessionScoped CDI bean与JSF ValueChangeListeners混合使用吗?
答案 0 :(得分:1)
@Inject
仅适用于CDI托管bean。您的ExampleValueChangeListener
不是CDI托管bean。
制作一个。最简单的方法是在其上放置@Named
注释,以便它可以在EL中使用。
@Named
public class ExampleValueChangeListener implements ValueChangeListener {
// ...
}
通过binding
而不是type
引用它。
<f:valueChangeListener binding="#{exampleValueChangeListener}" />