我想向 PrimeFaces 3.3 数据表添加排序功能,并创建了以下 ViewScoped bean 来存储列表,这样就不会一直从 EJB 中获取列表:
@Named
@ViewScoped
public class CustomerList implements Serializable {
private static final long serialVersionUID = 6168621124401208753L;
@EJB
CustomerEJB customerBean;
List<Customer> allCustomers = null;
public void loadCustomerList() {
allCustomers = customerBean.findAll();
}
public List<Customer> getList() {
if (allCustomers == null) {
loadCustomerList();
}
return allCustomers;
}
}
这是使用 bean 的 View :
<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:define name="content">
<h:form id="customerList">
<p:dataTable id="customer" var="customer"
value="#{customerList.list}" sortBy="#{customer.id}"
paginator="true" rows="10" paginatorAlwaysVisible="false"
paginatorPosition="top">
<p:column sortBy="#{customer.id}">
<f:facet name="header">
<h:outputText value="#{msg.customerIdLabel}" />
</f:facet>
<h:outputText value="#{customer.id}" />
</p:column>
<p:column sortBy="#{customer.lastName}">
<f:facet name="header">
<h:outputText value="#{msg.customerLastNameLabel}" />
</f:facet>
<h:outputText value="#{customer.lastName}" />
</p:column>
问题是我可以单击列标题进行排序,但表仍然未排序,即使初始排序也不起作用。当您在 getList() 方法中设置断点时,我可以看到在处理请求期间从 EJB 多次获取列表。 只要 View 通过 ViewScope 处于事件状态,bean 是否就不应被存储?
最佳答案
首先,与您的问题没有直接关系,但是: 您永远不应该将业务方法放入组件 getter 中(即使使用空检查,我认为这是一个不好的做法)。使用@PostConstruct注释代替:
@PostConstruct
public void loadCustomerList() {
allCustomers = customerBean.findAll();
}
public List<Customer> getList() {
return allCustomers;
}
每次构造 ViewScoped bean 时都会调用 loadCustomerList。 另外,检查导入的范围注释:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
最后你的类应该看起来像:
@ViewScoped
@ManagedBean
public class CustomerList implements Serializable {
...
}
关于sorting - JSF2/Primefaces dataTable 排序不适用于 ViewScoped bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229561/