【问题标题】:Order of execution of f:event causing exceptionf:event 的执行顺序导致异常
【发布时间】:2013-04-13 09:26:49
【问题描述】:

我正在尝试在页面加载时运行 f:event。 f:event 与支持 bean 函数 init() 相关联。 init() 创建会话对象toIndex,该对象在getStatusList() 函数中使用。但我面临的问题是getStatusList() 函数首先执行,因此它找不到toIndex 会话对象,它给了我一个空指针异常。 init() 函数永远不会被调用。 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);
    }


}

【问题讨论】:

    标签: jsf jsf-2 jstl facelets


    【解决方案1】:

    我认为,这里的问题是c:forEach。它在构建视图时执行(可能在触发事件之前)。尝试将其替换为ui:repeat。一般来说,c:forEach 与 JSF 一起使用时应小心(如果有的话),因为它有副作用。

    【讨论】:

    • 实际上我尝试使用 ui:repeat 但我遇到了问题,甚至尝试使用 h:dataTable 相同的情况。所以我只剩下c:forEach 的选项。有什么替代方法可以在getStatusList 之前触发init
    • ui:repeat 有什么问题?它通常应该具有类似的行为,并更好地集成到 JSF 中。
    • stackoverflow.com/questions/12501700/…。看看我的这个问题。很久以前就发过了
    • 我添加了链接问题的答案。
    • stackoverflow.com/questions/15186966/… 请你看看我的这个问题,如果我能解决这个问题,我可以很容易地在我的应用程序中使用 ui:repeat。
    猜你喜欢
    • 2013-03-28
    • 2021-09-25
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多