我试图在页面加载时运行f:event。f:event
与后台bean函数init()
相关联。init()
创建用于getStatusList()
函数的会话对象toIndex
。但我面临的问题是,getStatusList()
函数首先执行,因此它找不到toIndex
会话对象,它给我一个空指针异常。永远不会调用init()
函数。StatusBean
是会话作用域。
1)
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<f:view>
<f:event type="postAddToView" listener="#{statusBean.init}" ></f:event>
</f:view>
<h:head></h:head>
<h:body>
<c:forEach var="p" items="#{statusBean.statusList}"
varStatus="loop">
//content
</c:forEach>
</h:body>
</html>
2)背豆
public class StatusBean {
public List<Status> getStatusList() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
User user = (User) session.getAttribute("userdet");
Query query = em.createQuery("SELECT s FROM Status s WHERE s.email='"
+ user.getEmail() + "' ORDER BY s.timeMillis desc",
Status.class);
List<Status> results = query.getResultList();
Collections.sort(results);
int toIndex = (int) session.getAttribute("toIndex");
List<Status> subList = results.subList(0, toIndex);
return subList;
}
public void init(ComponentSystemEvent event) {
System.out.println("inside init");
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
int toIndex = 5;
session.setAttribute("toIndex",toIndex);
}
}
我认为,这里的问题是c:forEach
。它在构建视图时执行(可能在触发事件之前)。尝试将其替换为ui:repeat
。一般来说,c:forEach
在JSF中使用时应该小心(如果有的话),因为它有副作用。