代码之家  ›  专栏  ›  技术社区  ›  sergionni

h: jsf页面加载中显示的数据表内容,而不是仅单击commandLink

  •  2
  • sergionni  · 技术社区  · 14 年前

    看起来很简单,但不起作用)

    当加载.jsf页面时,将显示来自DB的值。
    dao impl块:

    public List<Product> getProducts() {
        return getHibernateTemplate().find("from Product");
    
    }
    

    托管bean块:

    public List<Product> getProducts() {
        return this.getProductManager().getProducts();
    }
    

    我是故意的 f:ajax 是否仅通过单击来执行此操作:

             <h:form>
    
                <h:commandLink value="show" action="nothing">
                    <f:ajax render="pr"/>
                </h:commandLink>
    
    
                <h:dataTable var="product" id="pr" value="#{showProducts.products}">
                      <h:column>#{product.name}</h:column>
                </h:dataTable>
    
             </h:form>
    

    数据加载后在页面上可见。 有了Firebug,我可以看到,这些数据是通过单击刷新的,所以ajax可以工作。

    我需要其他属性吗 h:dataTable 仅在单击时显示表内容的元素?

    谢谢您。

    1 回复  |  直到 14 年前
        1
  •  1
  •   BalusC    14 年前

    您需要在初始请求时隐藏datatable,并让commandlink在datatable的 rendered 属性取决于。

    小脸:

    <h:form>
        <h:commandLink value="show" action="#{showProducts.toggleShow}">
            <f:ajax render="products"/>
        </h:commandLink>
        <h:panelGroup id="products">
            <h:dataTable var="product" value="#{showProducts.products}" rendered="#{!showProducts.show}">
                <h:column>#{product.name}</h:column>
            </h:dataTable>
        </h:panelGroup>
    </h:form>
    

    豆子:

    private boolean show;
    
    public void toggleShow() {
        show = !show; // Or just show = true;
    }
    
    public boolean isShow() {
        return show;
    }
    

    也就是说,在getter中运行昂贵的业务/数据库逻辑并不是最佳实践。在比恩的一生中,getter可以被称为不止一次。而是在bean的构造函数或 @PostConstruct 方法。

    private List<Product> products;
    
    @PostConstruct
    public void init() {
        products = this.getProductManager().getProducts();
    }
    
    public List<Product> getProducts() {
        return products;
    }
    

    或者,如果它真的需要懒洋洋地加载,那么最好这样做:

    private List<Product> products;
    
    public List<Product> getProducts() {
        if (products == null) {
            products = this.getProductManager().getProducts();
        }
        return products;
    }