Home > Web Front-end > JS Tutorial > How to Invoke JSF Managed Beans on HTML DOM Events Using JavaScript?

How to Invoke JSF Managed Beans on HTML DOM Events Using JavaScript?

Linda Hamilton
Release: 2024-12-06 02:53:11
Original
1022 people have browsed it

How to Invoke JSF Managed Beans on HTML DOM Events Using JavaScript?

Invoking JSF Managed Bean on HTML DOM Event using Native JavaScript

In web development, it becomes necessary to execute server-side actions based on specific events occurring on the client-side. This is achievable in JavaServer Faces (JSF) by employing various approaches. One such approach is to invoke a JSF managed bean action method using Ajax during an HTML DOM load event.

JSF 2.3's

In JSF 2.3 and above, the component provides a direct solution:

<h:form>
    <h:commandScript name="commandName" action="#{bean.action}" render=":results" />
</h:form>
<h:panelGroup>
Copy after login

This script can be invoked using plain JavaScript:

commandName();
Copy after login
Copy after login

Setting autorun="true" triggers it during DOM load.

PrimeFaces

If PrimeFaces is utilized, consider employing its :

<h:form>
    <p:remoteCommand name="commandName" action="#{bean.action}" update=":results" />
</h:form>
<h:panelGroup>
Copy after login

Invocation is similar to :

commandName();
Copy after login
Copy after login

PrimeFaces uses jQuery for AJAX calls, not JSF native jsf.ajax.request().

OmniFaces

For JSF versions older than 2.3, OmniFaces offers , which serves the same purpose as :

<o:form>
    <o:commandScript name="commandName" action="#{bean.action}" render=":results" />
</o:form>
Copy after login

Simply replace h:commandScript with o:commandScript.

'Hidden Form' Trick

An alternative approach involves utilizing a hidden form with a :

<h:form>
Copy after login

Invocation:

document.getElementById("form:button").onclick();
Copy after login

Custom UIComponent

As a last resort, one can develop a custom UIComponent that extends UICommand and leverages jsf.ajax.request().

In summary, these approaches empower developers to invoke JSF managed beans on HTML DOM events using native JavaScript. The choice of method depends on factors such as JSF version, library usage, and project constraints.

The above is the detailed content of How to Invoke JSF Managed Beans on HTML DOM Events Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template