Close

PrimeFaces - Ajax ProgressBar Example

[Last Updated: Feb 10, 2018]

Following example shows how to use PrimeFaces ProgressBar which is updated based on the server side task progress via Ajax.

Example

JSF page

src/main/webapp/index.xhtml

<h:body>
    <h2>PrimeFaces - Ajax ProgressBar Example</h2>
    <h:form>

        <p:commandButton value="Perform long Task"
                         actionListener="#{taskView.startTask}"
                         onclick="jsStartTask()"
                         update="taskResult"
                         widgetVar="taskButton"/>
        <br/><br/>
        <p:progressBar  widgetVar="progressBar"
                        ajax="true"
                        interval="500"
                        value="#{taskView.progress}"
                        labelTemplate="{value}%"
                        global="false"
                        style="width:500px">

            <p:ajax event="complete"
                    update="taskResult"
                    oncomplete="jsOnComplete()"/>

        </p:progressBar>
        <h:outputText id="taskResult" value="#{taskView.result}"/>
    </h:form>

    <script type="text/javascript">
    function jsOnComplete() {
        PF('taskButton').enable();
    }

    function jsStartTask() {
      PF('taskButton').disable();
      PF('progressBar').cancel();
      PF('progressBar').setValue(0);
      PF('progressBar').start();
    }
 </script>
</h:body>
@ManagedBean
@ViewScoped
public class TaskView {
  private AtomicInteger progressInteger = new AtomicInteger();
  private ExecutorService executorService;

  public void startTask(ActionEvent ae) {
      executorService = Executors.newSingleThreadExecutor();
      executorService.execute(this::startLongTask);
  }

  private void startLongTask() {
      progressInteger.set(0);
      for (int i = 0; i < 100; i++) {
          progressInteger.getAndIncrement();
          //simulating long running task
          try {
              Thread.sleep(ThreadLocalRandom.current().nextInt(1, 100));
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
      executorService.shutdownNow();
      executorService = null;
  }

  public int getProgress() {
      return progressInteger.get();
  }

  public String getResult() {
      return progressInteger.get() == 100 ? "task done" : "";
  }
}

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

Ajax ProgressBar Example Select All Download
  • ajax-progress-bar-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also