Following example shows how to use PrimeFaces ProgressBar which is updated based on the server side task progress via Ajax.
<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" : ""; } }
Dependencies and Technologies Used: