2

我对DataTable - Lazy Loading有疑问。我认为问题出在IdiomasBean.java(TableBean.java 的等效项)中,如果我输入:

public IdiomasBean() {  }

public LazyDataModel<Idiomas> getLazyModel() {  
        lazyModel = new LazyIdiomasDataModel(idiomasBo.findAllIdiomas());
        return lazyModel;
}

我得到了正确的数据表,但是...... sortByfilterBy并且onRowSelect不工作。

public IdiomasBean() {  
        lazyModel = new LazyIdiomasDataModel(idiomasList);
}

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

我得到:java.lang.NullPointerException 这是堆栈跟踪:

> at
> brany.view.lazyDataModel.LazyIdiomasDataModel.load(LazyIdiomasDataModel.java:42)
>   at
> org.primefaces.component.datatable.DataTable.loadLazyData(DataTable.java:690)
>   at
> org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:192)
>   at
> org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:108)
>   at
> javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
>   at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
>   at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)    at
> javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
>   at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
>   at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
>   at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
>   at
> com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
>   at
> com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
>   at
> com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
>   at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)    at
> com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
>   at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)   at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
>   at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
>   at
> org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
>   at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
>   at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
>   at
> org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
>   at
> org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
>   at
> org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
>   at
> org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
>   at
> org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
>   at
> org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
>   at
> org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
>   at
> org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
>   at
> org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
>   at
> org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
>   at
> org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
>   at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
>   at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
>   at java.lang.Thread.run(Thread.java:722)

这是其余的代码:

索引.xhtml

<?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:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>PRUEBA PRIMEFACES</title>
    </h:head>
    <h:body>
<h:form id="form">
    <p:dataTable var="id" value="#{idiomasBean.lazyModel}" paginator="true" rows="10"
                 paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
                 rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{idiomasBean.selectedIdiomas}" id="idiomasTable" lazy="true">

        <p:ajax event="rowSelect" listener="#{idiomasBean.onRowSelect}" update=":form:display" oncomplete="idiomasDialog.show()" />

        <p:column headerText="Nombre" sortBy="#{id.nombre}" filterBy="#{id.nombre}">
            <h:outputText value="#{id.nombre}" />
        </p:column>

        <p:column headerText="Año" sortBy="#{id.name}" filterBy="#{id.name}">
            <h:outputText value="#{id.name}" />
        </p:column>

    </p:dataTable>

    <p:dialog header="Detalles Idioma" widgetVar="idiomasDialog" resizable="false"
              showEffect="explode" hideEffect="explode">

        <h:panelGrid id="display" columns="2" cellpadding="4">

            <h:outputText value="Nombre:" />
            <h:outputText value="#{idiomasBean.selectedIdiomas.nombre}" style="font-weight:bold"/>

            <h:outputText value="Valoración:" />
            <h:outputText value="#{idiomasBean.selectedIdiomas.valoracion}" style="font-weight:bold"/>

        </h:panelGrid>
    </p:dialog>
</h:form>
    </h:body>
</html>

idiomasBean.java

package brany.spring.managedBean;

import brany.model.bo.imp.IdiomasBo;
import brany.model.entityBean.Idiomas;
import brany.view.lazyDataModel.LazyIdiomasDataModel;
import java.util.List;
import org.primefaces.model.LazyDataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller  
@Scope("session")
public class IdiomasBean implements java.io.Serializable {
    private String nombre;
    private String name;

    @Autowired
    private IdiomasBo idiomasBo;

    private List<Idiomas> idiomasList;

    private LazyDataModel<Idiomas> lazyModel;
    private Idiomas selectedIdiomas;

    public IdiomasBean() {  
        lazyModel = new LazyIdiomasDataModel(idiomasList);
    }

    public void setIdiomasBo (IdiomasBo idiomasBo) {
        this.idiomasBo = idiomasBo;
    }

    public List<Idiomas> getIdiomasList() {
        idiomasList = idiomasBo.findAllIdiomas();
        return idiomasList;
    }

    public IdiomasBo getIdiomasBo () {
        return idiomasBo;
    }

    public String getNombre() {
        return this.nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

    public Idiomas getSelectedIdiomas() {  
        return selectedIdiomas;  
    }  

    public void setSelectedIdiomas(Idiomas selectedIdiomas) {  
        this.selectedIdiomas = selectedIdiomas;  
    } 
}

LazyIdiomasDataModel.java

package brany.view.lazyDataModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import brany.model.entityBean.Idiomas;
import brany.view.util.LazySorter;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

public class LazyIdiomasDataModel extends LazyDataModel<Idiomas> {

    private List<Idiomas> datasource;

    public LazyIdiomasDataModel(List<Idiomas> datasource) {
        this.datasource = datasource;
    }

    @Override
    public Idiomas getRowData(String rowKey) {
        for(Idiomas idiomas : datasource) {
            if(idiomas.getNombre().equals(rowKey))   
                return idiomas;
        }

        return null;
    }

    @Override
    public Object getRowKey(Idiomas idiomas) {
        return idiomas.getNombre();                 
    }

    @Override
    public List<Idiomas> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
        List<Idiomas> data = new ArrayList<Idiomas>();

        //filter
        for(Idiomas idiomas : 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(idiomas.getClass().getField(filterProperty).get(idiomas));

                    if(filterValue == null || fieldValue.startsWith(filterValue)) {
                        match = true;
                    }
                    else {
                        match = false;
                        break;
                    }
                } catch(Exception e) {
                    match = false;
                } 
            }

            if(match) {
                data.add(idiomas);
            }
        }

        //sort
        if(sortField != null) {
            Collections.sort(data, new LazySorter(sortField, sortOrder));
        }

        //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;
        }
    }
}

IdiomasBo.java

package brany.model.bo.imp;

import brany.model.bo.IIdiomasBo;
import brany.model.dao.imp.IdiomasDao;
import brany.model.entityBean.Idiomas;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class IdiomasBo implements IIdiomasBo {

    private IdiomasDao idiomasDao;

    public void setIdiomasDao (IdiomasDao idiomasDao) {
        this.idiomasDao = idiomasDao;
    }

    @Override
    public List<Idiomas> findAllIdiomas() {
        return this.idiomasDao.findAllIdiomas();
    }   
}

IdiomasDao.java

package brany.model.dao.imp;

import brany.model.dao.IIdiomasDao;
import brany.model.entityBean.Idiomas;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class IdiomasDao extends HibernateDaoSupport implements IIdiomasDao {
    @Override
    public List<Idiomas> findAllIdiomas() {      
        return getHibernateTemplate().find("from Idiomas");
    }
}

成语.java

package brany.model.entityBean;

public class Idiomas  implements java.io.Serializable {
     private Integer ididioma;
     private String nombre;
     private String name;

    public Idiomas() {
    }

    public Idiomas(String nombre, String name) {
       this.nombre = nombre;
       this.name = name;
    }

    public Integer getIdidioma() {
        return this.ididioma;
    }

    public void setIdidioma(Integer ididioma) {
        this.ididioma = ididioma;
    }
    public String getNombre() {
        return this.nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

LazySorter.java

package brany.view.util;

import java.util.Comparator;
import brany.spring.util.ReflectionUtil;
import org.primefaces.model.SortOrder;

public class LazySorter<T> implements Comparator<T> {

    private String sortField;
    private SortOrder sortOrder;

    public LazySorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(Object first, Object second) {
        try {
            Object value1 = ReflectionUtil.getValue(first, sortField);
            Object value2 = ReflectionUtil.getValue(second, sortField);

            int value = 0;

            if(value1 instanceof Comparable)
                value = ((Comparable) value1).compareTo(value2);
            else if(value1 instanceof Boolean && !value1.equals(value2))                
                value = (Boolean)value1 ? 1 : -1; 

            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

ReflectionUtil.java

package brany.spring.util;

public class ReflectionUtil {
    public static Object getValue(Object object, String fieldName) {
        try {
            String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
            return object.getClass().getMethod(getterName).invoke(object);
        } catch (Exception e) {
            return null;
        }
    }
}

面孔-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.1"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">

    <application>
            <!-- Estamos activando el soporte de Spring para la inyección de dependencias 
            de tal forma que JSF sabrá que si no encuentra un bean bajo su contexto debe 
            ir a buscarlo al contexto de Spring -->
            <el-resolver>
                    org.springframework.web.jsf.el.SpringBeanFacesELResolver
            </el-resolver>
    </application>

        <!-- Definimos el bean que va a trabajar con la aplicación que tiene asociada la 
        clase IdiomasBean y seteamos el atributo (property) idiomasBo-->
    <managed-bean>
        <managed-bean-name>idiomasBean</managed-bean-name>
        <managed-bean-class>brany.spring.managedBean.IdiomasBean</managed-bean-class>

        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>idiomasBo</property-name>
            <value>#{idiomasBo}</value>
        </managed-property>
        </managed-bean>

</faces-config>

有没有人有任何解决方案?

谢谢!

4

1 回答 1

3

试试这个你的 LazySorter 类应该通过不工作来修复排序

public class LazySorter implements Comparator<Idiomas> {


    private String sortField;

    private SortOrder sortOrder;

    /**
     * initializing sorting field and sorting order
     * @param sortField
     * @param sortOrder
     */
    public LazySorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }

    /**
     * Comparing object1 and object2 with reflection
     * @param object1
     * @param object2
     * @return
     */
    @Override
    public int compare(Idiomas object1, Idiomas object2) {
        try {
            Field field1 = object1.getClass().getDeclaredField(this.sortField);
            Field field2 = object2.getClass().getDeclaredField(this.sortField);
            field1.setAccessible(true);
            field2.setAccessible(true);
            Object value1 = field1.get(object1);
            Object value2 = field2.get(object2);

            int value = ((Comparable)value1).compareTo(value2);
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        }
        catch(Exception e) {
            throw new RuntimeException();
        }
    }
}
于 2014-10-25T01:23:01.693 回答