Close

PrimeFaces - Using RemoteCommand to send TimeZone offset from JavaScript to Managed bean.

[Last Updated: Jul 19, 2017]

In this example, we will learn how to use RemoteCommand to execute backing bean methods from javascript.

This example also provides a way to find client's time zone offset on the JSF managed bean side. There's a standard header 'Accept-Language' which can help us to find the client's locale, but there's no standard header to get client's time zone information on the server side. Though on the client side, we can use JavaScript's Date#getTimeZoneOffset() to get that information.

JSF page

src/main/webapp/index.xhtml

<h:body style="margin-left:50px">
    <h2>PrimeFaces RemoteCommand Example</h2>
    <h:form>
        <p:remoteCommand name="updateTz" update="tz" actionListener="#{timeZoneBean.updateClientTz}"/>
        Client time zone offset:
        <b>
            <h:outputText id="tz" value="#{timeZoneBean.clientTzOffset}"/>
        </b>
    </h:form>

    <script type="text/javascript">
    $(document).ready(function() {
        var date = new Date();
        var offSetVal = date.getTimezoneOffset();
        updateTz([{name:'offset',value:-offSetVal/60}]);
       });
    </script>
</h:body>

The manage bean

@ManagedBean
@RequestScoped
public class TimeZoneBean {

  @ManagedProperty("#{param.offset}")
  private String timeZoneOffset;
  private String clientTzOffset = "";

  public void updateClientTz() {
      Locale locale = FacesContext.getCurrentInstance()
                                  .getExternalContext()
                                  .getRequestLocale();

      if (timeZoneOffset != null && locale != null) {
          ZoneOffset offset = ZoneOffset.of(timeZoneOffset);
          clientTzOffset = offset.getDisplayName(TextStyle.FULL, locale);
      }
  }

  public String getClientTzOffset() {
      return clientTzOffset;
  }

  public void setTimeZoneOffset(String timeZoneOffset) {
      this.timeZoneOffset = timeZoneOffset;
  }
}

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

mvn tomcat7:run-war

Output

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

PrimeFaces Remote Command Example Select All Download
  • remote-command-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also