【问题标题】:h:commandButton inside h:dataTable [duplicate]h:commandButton 在 h:dataTable [重复]
【发布时间】:2011-04-26 11:04:09
【问题描述】:

我正在使用 JSF 数据表。表中的一列是命令按钮。

单击此按钮时,我需要使用表达式语言传递一些参数(例如所选行的值)。这些参数需要传递给 JSF 托管 bean,后者可以对其执行方法。

我使用了以下 sn-p 代码,但我在 JSF bean 上获得的值始终为空。

<h:column>
    <f:facet name="header">
        <h:outputText value="Follow"/>
    </f:facet>

    <h:commandButton id="FollwDoc" action="#{usermanager.followDoctor}" value="Follow" />
    <h:inputHidden id="id1" value="#{doc.doctorid}" />
</h:column>

豆方法:

public void followDoctor() {
    FacesContext context = FacesContext.getCurrentInstance();
    Map requestMap = context.getExternalContext().getRequestParameterMap();
    String value = (String)requestMap.get("id1");
    System.out.println("Doctor Added to patient List"+ value);
}

如何使用命令按钮将值传递给 JSF 托管 bean?

【问题讨论】:

    标签: jsf datatable


    【解决方案1】:

    使用DataModel#getRowData()获取当前行的action方法。

    @ManagedBean
    @ViewScoped
    public class Usermanager {
        private List<Doctor> doctors;
        private DataModel<Doctor> doctorModel;
    
        @PostConstruct
        public void init() {
            doctors = getItSomehow();
            doctorModel = new ListDataModel<Doctor>(doctors);
        }
    
        public void followDoctor() {
            Doctor selectedDoctor = doctorModel.getRowData();
            // ...
        }
    
        // ...
    }
    

    改为在数据表中使用它。

    <h:dataTable value="#{usermanager.doctorModel}" var="doc">
    

    并去掉视图中h:commandButton 旁边的h:inputHidden


    不那么优雅的替代方法是使用f:setPropertyActionListener

    public class Usermanager {
        private Long doctorId;
    
        public void followDoctor() {
            Doctor selectedDoctor = getItSomehowBy(doctorId);
            // ...
        }
    
        // ...
    }
    

    使用以下按钮:

    <h:commandButton action="#{usermanager.followDoctor}" value="Follow">
        <f:setPropertyActionListener target="#{usermanager.doctorId}" value="#{doc.doctorId}" />
    </h:commandButton>
    

    相关:

    【讨论】:

    • IMO,“不太优雅”的方法对于初学者来说似乎更直观。如何首选另一种方法?
    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2011-06-10
    • 2016-10-31
    • 2016-10-26
    • 2015-10-28
    • 2016-03-08
    • 2013-06-08
    相关资源
    最近更新 更多