我遇到了通过注入将值从bean传递到另一个bean的问题。
程序结构:用户搜索比萨饼,程序生成PizzaObjects并将其添加到列表'results'。现在我想将列表传递给bean PizzaResult。
我的ManagedBean看起来像这样:
@ManagedBean
@SessionScoped
public class PizzaSearch {
// variables
private List<PizzaObject> results = new ArrayList<PizzaObject>();
// methods to search for different pizzas
// methods to fill the list of PizzaObjects
// getter - setter
public List<PizzaObject> getResults() {
return results;
}
另一个bean的代码片段:
@ManagedBean
@SessionScoped
public class PizzaResult {
// injection
@ManagedProperty(value="#{pizzaSearch}")
private PizzaSearch pizzaSearch;
// variables
private List<PizzaObject> results;
@PostConstruct
public void initResults() {
results = pizzaSearch.getResults(); // results = empty
int size = results.size(); // size = 0
this._chosenSize = new int[size]; // chosenSize = 0
this._chosenQuantity = new int[size]; // chosenQuantity = 0
}
public void addToCart(int index) {
System.out.println("Parameter: " + results.get(index).getPizza().getPizzaID());
System.out.println("chosen size: " + getChosenSize()[index]);
System.out.println("chosen quantity: " + getChosenQuantity()[index]);
}
// getter and setter
我需要在PostConstruct中初始化结果,但不知何故,每个值都为0 ..
答案 0 :(得分:0)
@ManagedBean(name = "pizzaSearch")
(即使默认情况下已完成)。import javax.faces.bean.SessionScoped;
而不是import javax.enterprise.context.SessionScoped;
,请参阅有关此here 或者您可以使用 @Inject 注释:
基于CDI的bean定义
javax.enterprise.context.SessionScoped //for bean scoping
javax.inject.Named //for bean declaration
javax.inject.Inject //for injection
所以要将PizzaSearch managedBean注入PizzaResult,请按照以下步骤操作:
PizzaSearch 中的
@Named
@SessionScoped
public class PizzaSearch {
// your code here
和 PizzaResult
@Named
@SessionScoped
public class PizzaResult {
@Inject
PizzaSearch pizzaSearch;
//code here
还有另一种方法,如果您使用了SessionScoped,那么您可以使用FacesContext获取PizzaSearch的当前实例