Calling bean methods with arguments from JSF pages

前端 未结 3 755
长发绾君心
长发绾君心 2021-02-05 11:30

Is it possible to call bean methods & directly pass parameters to them from the view instead of requiring to first set the bean properties and then call methods without argu

相关标签:
3条回答
  • 2021-02-05 11:56

    Yes, it is.

    <h:commandButton action="#{bean.method(object)}" />
    

    See this http://www.mkyong.com/jsf2/4-ways-to-pass-parameter-from-jsf-page-to-backing-bean/

    0 讨论(0)
  • 2021-02-05 12:05

    You can call ManagedBean methods with arguments like this.

    <h:commandButton actionListener="#{stateBean.delete(row.stateID)}" 
     value="Delete" id="btnDeleteS">
    
       <f:ajax event="action" execute="@form" render="@form"/>
    </h:commandButton>
    

    The corresponding ManagedBean would be like this.

    @ManagedBean
    @RequestScoped
    public class StateBean
    {
        @EJB
        private RemoteInterface obj=null;
    
        public void delete(String stateID)
        {
            //Code stuff here.
        }
    }
    

    You can also directly set the value of ManagedBean properties using <f:setPropertyActionListener></f:setPropertyActionListener> like this.

    <h:commandButton value="Delete" id="btnDeleteS">
    
         <f:setPropertyActionListener target="#{stateBean.someProperty}"
           value="#{someValue}"/>
         <f:ajax event="action" execute="@form" render="@form"/>
    </h:commandButton>
    
    0 讨论(0)
  • 2021-02-05 12:07

    Passing method arguments is supported since EL 2.2 which is part of Servlet 3.0. So if your webapp runs on a Servlet 3.0 compatible container (Tomcat 7, Glassfish 3, etc) with a web.xml declared conform Servlet 3.0 spec (which is likely true as you're using JSF 2.1 which in turn implicitly requires Servlet 3.0), then you will be able to pass method arguments to bean action methods in the following form:

    <h:commandButton value="Submit" action="#{bean.submit(item.id)}" />
    

    with

    public void submit(Long id) {
        // ...
    }
    

    You can even pass fullworthy objects along like as:

    <h:commandButton value="Submit" action="#{bean.submit(item)}" />
    

    with

    public void submit(Item item) {
        // ...
    }
    

    If you were targeting a Servlet 2.5 container, then you could achieve the same by replacing the EL implementation by for example JBoss EL which supports the same construct. See also Invoke direct methods or methods with arguments / variables / parameters in EL.

    0 讨论(0)
提交回复
热议问题