如何传递参数或设置托管 Bean 的字段以从 addAction 获得适当的副作用?
我的 ManagedBean listaEntrada 有一个引用属性,但是我需要使用 ProductController Bean 从实体管理器获取描述。然后我需要调用 listaEntrada Bean 的 addAction 将该产品添加到产品列表中。
我的问题是如何传递从 productController 获得的值并设置我的 listaEntrada 控制器字段
是否可以/正确执行 value="#{listaEntrada.referencia}=#{productController.referencia}" ?
BalusC 等感谢您的回复,感谢您的回复和我的研究,该项目正在形成。
注意:我目前正在使用 JSF,但我将在最终产品上使用 Primefaces,因此使用 primefaces 命名空间。
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h1>Adicionar Referências</h1>
<h3>Lista de Referências</h3>
<h:form>
<table>
<tr>
<td>Referencia :</td>
<td>
<!-- <h:inputText size="10" value="#{listaEntrada.referencia}" />-->
<h:inputText value="#{produtoController.reference}"
onkeypress="if (event.keyCode == 13) {onchange(); return false; }">
<f:ajax event="change" render="textDescri" listener="#{produtoController.listener}"/>
</h:inputText>
</td>
</tr>
<tr>
<td>Descrição :</td>
<td>
<!-- <h:inputText size="20" value="#{listaEntrada.descricao}" />-->
<h:outputText id="textDescri" value="#{produtoController.replyWith}" />
</td>
</tr>
<tr>
<td>Quantidade :</td>
<td><h:inputText size="5" value="#{listaEntrada.quantidade}" /></td>
</tr>
<tr>
<!-- <p:calendar id="dataEntrada"
value="#{listaEntrada.dataEntrada}"
showOn="button"
inputStyle="width:100px;"
navigator="true"/>-->
</tr>
</table>
<h:commandButton value="Adicionar" action="#{order.addAction}" />
<h3>Lista de Produtos</h3>
<h:dataTable value="#{listaEntrada.itemList}" var="item"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>
<h:column>
<f:facet name="header">Referencia</f:facet>
#{item.referencia}
</h:column>
<h:column>
<f:facet name="header">Descrição</f:facet>
#{item.descricao}
</h:column>
<h:column>
<f:facet name="header">Quantidade</f:facet>
#{item.quantidade}
</h:column>
<h:column>
<f:facet name="header">Data Entrada</f:facet>
#{item.dataEntrada}
</h:column>
<h:column>
<f:facet name="header">Action</f:facet>
<h:commandLink value="Apagar" action="#{lista.deleteAction(item)}" />
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
这是我的 Bean 减去 getter 和 setter:
package Controllers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "listaEntrada")
@SessionScoped
public class ListaEntrada implements Serializable {
private static final long serialVersionUID = 1L;
//Fields
//Propriedades Produto
String referencia;
String descricao;
int quantidade;
Date dataEntrada;
//Propriedades de Localizacao
private String armazem;
private String corredor;
private String estante;
private String prateleira;
private static final ArrayList<ListItem> listItems =
new ArrayList<ListItem>(Arrays.asList(
new ListItem("1", "ProdutoFixo", new Date(), 11),
new ListItem("2", "ProdutoFixo", new Date(), 22))
);
//Operações de lista
//Retorna lista
public ArrayList<ListItem> getItemList() {
return listItems;
}
public String addAction() {
//Cria um objecto Order com os campos
ListItem item = new ListItem(this.getReferencia(), this.getDescricao(), this.getDataEntrada(), this.getQuantidade());
//Adiciona a orderList
listItems.add(item);
return null;
}
public String deleteAction(ListItem item) {
listItems.remove(item);
return null;
}
//ENTIDADE listItem
public static class ListItem {
String referencia;
String descricao;
Date dataEntrada;
int quantidade;
public ListItem(String ref, String des, Date dE, int qtt) {
this.referencia = ref;
this.descricao = des;
this.dataEntrada = dE;
this.quantidade = qtt;
}
}
}
这是我的 productController bean:
package Controllers;
import entities.Produto;
import Controllers.util.JsfUtil;
import Controllers.util.PaginationHelper;
import Session.ProdutoFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
@ManagedBean(name = "produtoController")
@SessionScoped
public class ProdutoController implements Serializable {
private Produto current;
private DataModel items = null;
private int Reference;
@ManagedProperty(value = "replyWith")
private String replyWith;
@EJB
private Session.ProdutoFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public ProdutoController() {
}
public void listener(AjaxBehaviorEvent event) {
if (getReference() >= 0) {
Produto returnProduto = getFacade().find(getReference());
if (returnProduto != null) {
String returnedName = returnProduto.getDescricao();
setReplyWith(returnedName);
} else {
setReplyWith("N/A");
}
System.out.println(getReplyWith());
}
System.out.println("I am Listening!");
}
public Produto getSelected() {
if (current == null) {
current = new Produto();
selectedItemIndex = -1;
}
return current;
}
private ProdutoFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Produto) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Produto();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutoCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Produto) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutoUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Produto) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProdutoDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
/**
* @return the Reference
*/
public int getReference() {
return Reference;
}
/**
* @param Reference the Reference to set
*/
public void setReference(int Reference) {
this.Reference = Reference;
}
/**
* @return the replyWith
*/
public String getReplyWith() {
return replyWith;
}
/**
* @param replyWith the replyWith to set
*/
public void setReplyWith(String replyWith) {
this.replyWith = replyWith;
}
@FacesConverter(forClass = Produto.class)
public static class ProdutoControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ProdutoController controller = (ProdutoController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "produtoController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Produto) {
Produto o = (Produto) object;
return getStringKey(o.getIdproduto());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ProdutoController.class.getName());
}
}
}
}