Monday, February 16, 2015

How to pass javascript parameters to JSF managed bean using RichFaces <a4j:param> component

In your JSF project if you are using RichFaces it is easy to send javascript values from your xhtml page to your managed bean using a4j:param component.
See below example.

My xhtml page is as below.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
  <script>
    var jsMessage = 'Hello from javascript!';

    function calculate() {
      return 100 + 50;
    }
  </script>
</h:head>
<body>
  <h:form>
    <a4j:commandButton action="#{test.doIt}" value="Do It">
      <a4j:param value="jsMessage" noEscape="true"
             assignTo="#{test.message}" />
      <a4j:param value="calculate()" noEscape="true"
             assignTo="#{test.valueFromFunction}" />
    </a4j:commandButton>
  </h:form>
</body>
</html>

This is my managed bean.
import javax.faces.bean.ManagedBean;

@ManagedBean(name="test")
public class Test {
  private String message;
  private Double valueFromFunction;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public Double getValueFromFunction() {
    return valueFromFunction;
  }

  public void setValueFromFunction(Double valueFromFunction) {
    this.valueFromFunction = valueFromFunction;
  }

  public void doIt() {
    System.out.println("Message : " + message);
    System.out.println("Value From Function : " + valueFromFunction);
  }
}

No comments:

Post a Comment