3

パラメータを渡したり、マネージド Bean のフィールドを設定したりして、addAction から適切な副作用を得るにはどうすればよいですか?

私の ManagedBean listaEntrada には参照されるプロパティがありますが、Entity Manager から説明を取得するには 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からゲッターとセッターを除いたものです:

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());
            }
        }
    }
}
4

1 に答える 1

4

私は次のように定義します。

<html xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">

また、f:setPropertyActionListener を使用して、ManagedBean から別の ManagedBean にパラメーターを渡すことができます。

<h:commandButton image="buscar.png" action="#{bean2.addData}"
    immediate="true" >
    <f:setPropertyActionListener target="#{bean2.data}" value="#{bean1.data}" />
    <f:setPropertyActionListener target="#{bean2.strReference}" value="test" />
</h:commandButton>

[編集] a4j を h に変更

于 2012-08-20T15:57:14.237 に答える