PrimeFaces - Invoking Javascript from a Bean

[Updated: Sep 23, 2017, Created: Sep 19, 2017]

This example shows how to use Primefaces RequestContext#execute() method to invoke Javascript. A RequestContext has several helpful methods. The execute() method can invoke client side Javascript code during an ajax or non-ajax request.

JSF page

src/main/webapp/index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
<h:head>
    <script type="application/javascript">
       function handleMsg(msg){
        alert(msg);
    }

    </script>
</h:head>
<h:body>
    <h2>RequestContext - Invoking JavaScript from bean example</h2>
    <h:form>
        <h:outputText value="#{myBean.time}"/>
        <br/>
        <p:commandButton value="Click Me"
                         actionListener="#{myBean.handleClick}"/>
    </h:form>
</h:body>
</html>
@ManagedBean
@ViewScoped
public class MyBean {

  @PostConstruct
  public void init() {
      RequestContext.getCurrentInstance()
                    .execute("handleMsg('invoked from post construct');");
  }

  public void handleClick(ActionEvent actionEvent) {
      RequestContext.getCurrentInstance()
                    .execute("handleMsg('invoked from bean listener');");
  }

  public String getTime() {
      return LocalTime.now().toString();
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

On page load:

On button click:

Example Project

Dependencies and Technologies Used :

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

RequestContext#execute() example Select All Download
  • execute-js-from-bean
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also