Calling a backing bean method from within jquery

2019-07-20 14:52发布

问题:

Im working on a JSF file where I have a javascript function, and some jquery involved in this. I have designed a dialog with two button: 1) Ok and 2) Cancel. I have designed it in such a way that the Cancel button will abort the process, and there is no problem with that.
But, what I want to accomplish is that when the user presses Ok then the program should call a backing bean(java bean) method, Have anyone of you been able to manage this?

Thankful for all your help & tip

回答1:

To the point, you need to let jQuery trigger the click event on the HTML representation of a JSF <h:commandButton>. You could if necessary hide the form/button with CSS display:none.

E.g.

<h:form id="formId" style="display:none">
    ...
    <h:commandButton id="buttonId" ... />
</h:form>

with

$("[id='formId:buttonId']").click();

This is however somewhat clumsy. Why not just using the <h:commandButton> directly as "OK" button? Further, reinventing jQuery based components for JSF may in long term be a pain. Have you looked at for example PrimeFaces to save yourself the headache and boilerplate code? It is using jQuery and jQuery UI under the covers already. See also e.g. <p:confirmDialog> showcase.

See also:

  • What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?


回答2:

I think you just need this :

<h:form>
   <h:commandButton value="OK" action="#{bean.submit}" />
</h:form>


回答3:

If you include richfaces, you can use rich jsFunction component to call action method of you backing bean you can see http://livedemo.exadel.com/richfaces-demo/richfaces/jsFunction.jsf;jsessionid=168EE2D49DC8BB1BA781B1C880B4B511?c=jsFunction&tab=usage

<a4j:jsFunction name="pressOK" reRender="showname" action="#{bean.action}" oncomplete="callback()">

    </a4j:jsFunction>

with this, you can call javascript function pressOK()