El bean ViewScoped se recrea cada vez que hago clic en el botón de comando en mi tabla de datos

StackOverflow https://stackoverflow.com/questions/9500439

Pregunta

Estoy usando Primefaces versión 3.1.1, Mojarra 2.1.3, Netbeans 7.0.1, Glassfish Server 3.1.

Mi aplicación de prueba utiliza una plantilla facelet con diseño superior, izquierdo, de contenido, derecho e inferior con divs y CSS sin formato.Después de que el usuario inicie sesión con jdbcrealm administrado por contenedor, se le presentará el index.html principal que utiliza dicha plantilla.

Puse un menú de navegación en el panel izquierdo que posteriormente actualizará el contenido del panel central con ajax al hacer clic en el elemento del menú.El panel central se actualizará dinámicamente en <ui:include> mediante el uso de sessionScoped NavigationBean.

en una de las paginas clientList.xhtml, Yo puse un <p:dataTable> con un botón para ver el detalle haciendo aparecer una <p:dialog>.Estoy usando un bean viewCoped para contener la lista de datos que se muestra en la tabla de datos.

El problema es que cuando hago clic en el botón para seleccionar una fila en la última columna de cada fila, el cuadro de diálogo no aparece en absoluto y mi p:ajaxStatus La imagen gif seguía rodando sin cesar.Cuando depuro el programa con netbeans, noto que se vuelve a llamar al constructor y la instancia anterior desaparece después de hacer clic en el botón.

Este es mi index.xhtml usando la plantilla de facetas.

<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"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition template="/BySalesAutomationTemplate.xhtml">
    <ui:define name="title">
        <h:outputText value="Facelet Index Page"></h:outputText>
    </ui:define>
    <ui:define name="top">
        TOP
    </ui:define>
    <ui:define name="left">
        <ui:include src="users/menu#{request.isUserInRole('ADMIN') ? 'Admin' : 'User'}.xhtml" />
    </ui:define>
    <ui:define name="right">
        <h:outputText value="Cuba2 daan"></h:outputText>
    </ui:define>
    <ui:define name="maincontent">
        <c:if test="#{navigationBean.page!=null}">
            <ui:include src="#{navigationBean.page}.xhtml" />
        </c:if>
    </ui:define> 
    <ui:define name="bottom">
        <center>2012</center> 
    </ui:define>
  </ui:composition>
</html>

Este es el clientList.xhtml página que se muestra en el panel central de mi index.xhtml al hacer clic en un enlace en el menú del panel izquierdo.

<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>Client Listing</title>
</h:head>
<h:body>
    <p>Client List</p>
    <h:form>
        <h:commandButton action="#{authBackingBean.logout}" value="Logout" />
    </h:form>
    <f:view>
        <h:form id="formdetail" prependId="false">
            <p:ajaxStatus>
                <f:facet name="start">
                    <h:graphicImage value="images/loading.gif" />
                </f:facet>
                <f:facet name="complete">
                    <h:outputText value="" />
                </f:facet>
            </p:ajaxStatus>
            <p:growl id="growl" showDetail="true"/>
            <p:dataTable id="dtClientList" value="#{saClientController.lazyModel}" rowsPerPageTemplate="10,20,30,50" 
                         paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}" 
                         paginatorAlwaysVisible="false" var="item" paginator="true" rows="10">
                <f:facet name="header">
                    <h:outputText value="Client List"/>
                </f:facet>
                <p:column filterBy="#{item.idSaClient}">
                    <f:facet name="header">
                        <h:outputText value="IdSaClient"/>
                    </f:facet>
                    <p:commandLink action="#{saClientController.showDetails(item)}" value="#{item.idSaClient}" target=":maincontent"/>                        
                </p:column>
                <p:column filterBy="#{item.saClientName}">
                    <f:facet name="header">
                        <h:outputText value="saClientName"/>
                    </f:facet>
                    <h:outputText value="#{item.saClientName}"/>
                </p:column>
                <p:column filterBy="#{#item.saClientAddress}">
                    <f:facet name="header">
                        <h:outputText value="SaClientAddress"/>
                    </f:facet>
                    <h:outputText value="#{item.saClientAddress}"/>
                </p:column>
                <p:column style="width:40px">  
                    <h:panelGrid columns="3" styleClass="actions" cellpadding="2">  
                        <p:commandButton id="selectButton" update=":formdetail:display" oncomplete="clientDialog.show()" icon="ui-icon-search" title="View">                                  
                            <f:setPropertyActionListener value="#{item}" target="#{saClientController.selectedSaClient}" />  
                        </p:commandButton>  
                    </h:panelGrid>  
                </p:column>  
                <f:facet name="footer">
                    <h:outputText value="Client List"/>
                </f:facet>
            </p:dataTable>                      
        </h:form>

        <p:dialog id="clientDialog" header="Client Detail" widgetVar="clientDialog" resizable="false" showEffect="explode" hideEffect="explode">
            <h:panelGrid id="display" columns="2" cellpadding="4"> 
                 <f:facet name="header"> 
                     <h:outputText value="Selected Row" />
                 </f:facet> 
                 <h:outputText value="ID" />
                 <h:outputText value="#{saClientcontroller.selectedSaClient.idSaClient}" />
                 <h:outputText value="NAME:" /> 
                 <h:outputText value="#{saClientcontroller.selectedSaClient.saClientName}" /> 
                 <h:outputText value="DESCRIPTION:" />  
                 <h:outputText value="#{saClientcontroller.selectedSaClient.saClientAddress}" />  
             </h:panelGrid>
        </p:dialog>                   

    </f:view>
  </h:body>
</html>

Este es mi Backing Bean.

public class SaClientController implements Serializable {

    @EJB
    private SaClientFacade saClientFacade;
    private SaClient selectedSaClient;
    private LazyDataModel<SaClient> lazyModel;
    private List<SaClient> saclients;

    /** Creates a new instance of SaClientController */
    public SaClientController() {
    }

    @PostConstruct
    public void Init() {
        saclients = saClientFacade.Retrieve();
        lazyModel = new LazyDataModelImp(saclients);
    }

    public LazyDataModel<SaClient> getLazyModel() {
        return lazyModel;
    }

    public List<SaClient> getClients() {
        return saClientFacade.Retrieve();
    }

    public SaClient getDetails() {
        return selectedSaClient;
    }

    public String showDetails(SaClient selectedSaClient) {
        this.selectedSaClient = selectedSaClient;
        return "DETAILS";
    }

    public String update() {
        System.out.println("###UPDATE###");
        selectedSaClient = saClientFacade.Update(selectedSaClient);
        return "SAVED";
    }

    public String list() {
        System.out.println("###LIST###");
        return "LIST";
    }

    public SaClient getSelectedSaClient() {
        return selectedSaClient;
    }

    public void setSelectedSaClient(SaClient selectedSaClient) {
        this.selectedSaClient = selectedSaClient;
    }

    public String dummyAction()
    {
        return null;
    }
}

Este es el LazyModelImp clase

public class LazyDataModelImp extends LazyDataModel<SaClient> {

    private List <SaClient> datasource;

    public LazyDataModelImp(List<SaClient> datasource) {
        this.datasource = datasource;
    }

    @Override
    public SaClient getRowData(String rowKey) {
        for (SaClient saclient : datasource) {
            if (saclient.getIdSaClient().toString().equals(rowKey)) {
                return saclient;
            }
        }
        return null;
    }

    @Override
    public Object getRowKey(SaClient saclient) {
        return saclient.getIdSaClient().toString();
    }

    @Override
    public List<SaClient> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        List<SaClient> data = new ArrayList<SaClient>();
        //filter        
        for (SaClient saclient : datasource) {
            boolean match = true;
            for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
                try {                    
                    String filterProperty = it.next();
                    String filterValue = filters.get(filterProperty);
                    String fieldValue = String.valueOf(saclient.getFilterSortFieldValue(filterProperty));
                    if (filterValue == null || fieldValue.startsWith(filterValue.toUpperCase()) || fieldValue.startsWith(filterValue.toLowerCase())) {
                        match = true;
                    } else {
                        match = false;
                        break;
                    }
                } catch (Exception e) {
                    match = false;
                }
            }
            if (match) {
                data.add(saclient);
            }
        }
        //rowCount
        int dataSize = data.size();
        this.setRowCount(dataSize);
        //paginate
        if (dataSize > pageSize) {
            try {
                return data.subList(first, first + pageSize);
            } catch (IndexOutOfBoundsException e) {
               return data.subList(first, first + (dataSize % pageSize));
            }
        }
        else {
            return data;
        }
        //sort
        //if (sortField != null) {
        //    Collections.sort(data, new LazySorter(sortField, sortOrder));
        //}       
        //return data;
    }
}

Ya deshabilité el ahorro de estado parcial en web.xml.

<context-param> 
    <param-name>javax.faces.PARTIAL_STATE_SAVING</param-name> 
    <param-value>false</param-value> 
</context-param> 

El backingBean se reinicia la primera vez que hago clic en el botón de comando ver detalles en la última columna de la tabla de datos en clienList.xhtml.Y el cuadro de diálogo no se muestra en absoluto.Pero después de presionar F5.El cuadro de diálogo se puede mostrar pero sin ningún contenido, lo único que se muestra en el cuadro de diálogo es la etiqueta texto de salida pero no los valores del bean, están vacíos.Perdón por la pregunta de novato.Estaría muy contento si alguien pudiera decirme que lo que estoy haciendo está mal, y tal vez un pequeño consejo sobre la navegación y si mi estrategia de mostrar todo en index.xhtml (Así que solo tengo 1 ID de vista todo el tiempo, que es index.xhtml, ¿verdad?) tiene razón.

¿Fue útil?

Solución

Este puede ser el problema con el cuadro de diálogo de PrimeFaces que tiene h:form rodeando el p:dialog.He notado que el cuadro de diálogo PrimeFaces no funciona correctamente cuando es un elemento secundario de un elemento de formulario.

Intente colocar este formulario de diálogo dentro del contenido del diálogo.

<p:dialog id="clientDialog" header="Client Detail" widgetVar="clientDialog" resizable="false" showEffect="explode" hideEffect="explode">
  <h:form id="formdialog" prependId="false">
    <h:panelGrid id="display" columns="2" cellpadding="4">
    ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top