【问题标题】:Insert/Add JSF component at render time在渲染时插入/添加 JSF 组件
【发布时间】:2012-03-10 11:31:40
【问题描述】:

是否可以在渲染期间添加子组件?如果不是,那么在 JSF 1.2 环境中动态添加子组件的最佳实践是什么?谢谢

【问题讨论】:

  • 你有具体的例子吗?
  • 基本上我想创建一个带有变量的组件假设它是一个布尔值,如果它是真的,我想在组件内添加一个子输入,所以它最终会成为一个 div在内部使用输入的渲染器类而不是在顶部组件的渲染器中渲染它。
  • 我知道用 Seam 很容易做到,但不是 100% 肯定只用 jsf。试试这个coderanch.com/t/212933/JSF/java/if-like-JSF-conditions,它提到了可能会成功的panelGroup
  • 不完全是我想要的,我希望面板的孩子成为组件,而不仅仅是通过 html。

标签: jsf jakarta-ee


【解决方案1】:

在 PhaseListener 实现中可以做到这一点的更好的地方。

例如,下一个代码 sn-p 示例如何将新组件添加到视图根:

public class ViewModifierPhaseListener implements
        javax.faces.event.PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
    }

    // Just sampling add component on ViewRoot
    @Override
    public void beforePhase(PhaseEvent event) {
        // Gets the target component from ViewRoot
        UIViewRoot viewRoot = event.getFacesContext().getViewRoot();
        UIComponent parent = viewRoot.findComponent("parentComponentId");
        // UIComponents to create depend on JSF implementation, 
        // Try to use the available factories when suplied by the implementation
        UIComponent child = Factory.getComponent("ComponentClassName");
        // Customize the component, for instance it has to be disabled
        child.getAttributes().put("disabled", true);
        // Adds the fresh created component to the parent
        parent.getChildren().add(child);
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }
}

请注意,getPhaseId 返回 RENDER_RESPONSE 阶段,因为在该阶段您完成了组件树。

您的阶段监听器定义必须像这样在 faces-config.xml 的生命周期元素中设置:

<lifecycle>
    <phase-listener>your.package.ViewModifierPhaseListener</phase-listener>
</lifecycle>

或者,如果您使用 facelets,您可以在您希望受侦听器影响的页面模板中定义它。这有助于您区分何时执行 PhaseListener。

<f:phaseListener type="your.package.ViewModifierPhaseListener"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2011-02-06
    • 2011-07-07
    • 2011-09-03
    • 2011-12-12
    • 1970-01-01
    相关资源
    最近更新 更多