0

我正在尝试在页面加载时运行 f:event。f:event与支持 bean 功能相关联init()。创建在函数中使用的init()会话对象。但是我面临的问题是函数首先执行,因此它找不到会话对象,并且它给了我一个空指针异常。该函数永远不会被调用。是会话范围的。toIndexgetStatusList()getStatusList()toIndexinit()StatusBean

1)xhtml

<!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);
    }


}
4

1 回答 1

1

I think, the problem here is the c:forEach. It is executed when the view is built (probably before the event is triggered). Try to replace it with ui:repeat. Generally, c:forEach should be used with care (if at all) with JSF as it has side effects.

于 2013-04-13T09:38:41.617 回答