Page 4 of 6
Building the JSF Managed Beans
Creating managed beans has never bean easier: you don't need any more declaring them in faces-config.xml. It's enough to declare them as annotation with the @ManagedBean annotation.
The first bean we will write is the @RequestScoped StoreManager JSF Bean which acts as a facade between the JSF page and the EJBs.
package control;
import java.util.*;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import view.CustomerView;
import view.ItemView;
import ejb.StoreManagerDao;
import model.Customer;
import model.Item;
@ManagedBean()
@RequestScoped
public class StoreManager {
@Inject
private StoreManagerDao storeManager;
@ManagedProperty(value="#{customerView}")
private CustomerView customerView;
@ManagedProperty(value="#{itemView}")
private ItemView itemView;
List<Item> listOrders;
List <SelectItem> listCustomers;
public StoreManager() { }
// Getters and setters here ...
public void findOrders() {
listOrders = storeManager.findAllItems(customerView.getCustomerId());
}
public void findAllCustomers() {
List<Customer> listCustomersEJB = storeManager.findAllCustomers();
for (int ii=0;ii<listCustomersEJB.size();ii++) {
Customer customer = listCustomersEJB.get(ii);
listCustomers.add(new SelectItem(customer.getId(),customer.getName()));
}
}
public void saveOrder() {
storeManager.saveItem
(customerView.getCustomerId(),itemView.getOrderPrice(),itemView.getOrderQuantity(),itemView.getOrderProduct());
FacesMessage fm = new FacesMessage("Saved order for "+itemView.getOrderQuantity()+ " of "+itemView.getOrderProduct());
FacesContext.getCurrentInstance().addMessage("Message", fm);
}
public void insertCustomer() {
storeManager.createCustomer(customerView.getCustomerCountry(), customerView.getCustomerName());
FacesMessage fm = new
FacesMessage("Created Customer "+customerView.getCustomerName()+ " from "+customerView.getCustomerCountry());
FacesContext.getCurrentInstance().addMessage("Message", fm);
// Forces customer reloading
this.listCustomers=null;
}
public List<SelectItem> getListCustomers() {
if (listCustomers == null) {
listCustomers= new ArrayList();
findAllCustomers();
}
return listCustomers;
}
public void setListCustomers(List<SelectItem> listCustomers) {
this.listCustomers = listCustomers;
}
}
Things to notice:
1) The StoreManagerDao EJB is injected into the JSF Managed Bean using the annotation
@Inject
private StoreManagerDao storeManager;
2) The other Managed Beans used in this project (to handle the form attributes) are injected using the @ManagedProperty annotation:
@ManagedProperty(value="#{customerView}")
private CustomerView customerView;
@ManagedProperty(value="#{itemView}")
private ItemView itemView;