Ways to display a progress bar on a JSP page to visually indicate the progression of a Java servlet's execution

After reviewing my previous posts addressing this question, I am still struggling to figure out how to implement it in my program. Here is what I need:

From a JSP page, I make an AJAX call to a servlet like this:

$(document).on('click' , '#gettopevents' , function(event) {


            var field = $("input[name = 'field']").val(); 

            if(field === "")
            {
                $('#responsemsg').html("Please enter a field");
            }
            else
            {
                var dataform = { 'field' : field };

                $.ajax({
                        url : 'GetAllLogs',
                        type : 'POST' , 
                        data : dataform , 
                        success : function(response) {
                            $('#displaylist').load('listgeneration.jsp');
                        },
                        error : function(){
                            alert("Error occurred");
                        }
                });
            }

            event.preventDefault();
    });

The servlet execution is a lengthy process and requires some time. Therefore, I want to display a progress bar to indicate the status of the servlet's execution. Specifically, I would like it to work like this:

@WebServlet("/GetAllLogs")
public class GetAllLogs extends HttpServlet
{
    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException  
    {
          PrintWriter obj = response.getWriter();
          obj.print(10);
          // Set progress bar value to 10%

          ....
          ....

          obj.print(40);
          // Change progress bar value to 40%
         .....
         .....

          obj.print(100);
           //Change progress bar value to 100%
    }
}

I essentially need to update the progress bar for every print value in the servlet. Is this approach feasible, and if so, how can I achieve it? Thank you in advance.

Answer №1

These are the fundamental steps:

  1. The initial ajax call triggers a lengthy process and returns promptly.
  2. The lengthy process is aware of its duration and can indicate how far it has progressed.
  3. Another endpoint supplies the status of the lengthy process. Subsequently, another ajax call is made every second (or as deemed appropriate) to retrieve the data for display in the progress bar.

*A simple approach would be using an AtomicInteger stored in the session, which updates as the lengthy process completes tasks. However, if the lengthy process is on a different JVM or the status-providing endpoint is on a separate JVM, the initial call should assign a unique token to the process. The lengthy process updates shared storage, like a database, using the token as the key. This token is passed to the status endpoint to fetch the status.

edit for additional context

Ajax call to

Upon the return of this ajax call, it initializes another method that initiates backend polling. (Referencing this other post.)

        $.ajax({
                    url : https://.../api/long/running/process/start,
                    type : 'POST' , 
                    data : dataform , 
                    success : function(response) {
                        pollForLongRunningStatus(response);
                    },
                    error : function(){
                        alert("error");
                    }
            });
        }

        pollForLongRunningStatus(response) {
           $.post('https://.../api/long/running/process/status', function(data) {
           alert(data);  // update the progress bar
           setTimeout(pollForLongRunningStatus, 1000);
          });
        }

If the start URL is handled by the following class - it's crucial for this class to begin the lengthy process and return swiftly, requiring asynchronous processing. (Implementation depends on the backend framework, if any.)

@WebServlet("/.../api/long/running/process/start")
public class LongRunningProcessStartHandler extends HttpServlet  {
    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException  {

    AtomicInteger percentComplete = new AtomicInteger(0);
    request.getSession().setAttribute("LONG_RUNNING_PROCESS_STATUS", percentComplete);

    LongRunningProcess lrp = new LongRunningProcess(percentComplete);
    lrp.start();

}

public class LongRunningProcess extends Thread {
   private final AtomicInteger percentComplete;

   public LongRunningProcess(AtomicInteger percentComplete) {
       this.percentComplete = percentComplete;
   }

   public void run() {
       for (int i = 0; i < 100; i++) {
       Thread.sleep(1000);
       percentComplete.incrementAndGet();
   }
}

Meanwhile, the status URL only reports the percentage completion. Suppose this class handles the status endpoint:

@WebServlet("/.../api/long/running/process/status")
public class LongRunningProcessStatusHandler extends HttpServlet  {
    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException  {

    return request.getSession().getAttribute("LONG_RUNNING_PROCESS_STATUS").get();
}

This outlines the procedure. (The code above requires compilation adjustments and null-safety considerations.) When the value reaches 100, remove the object from the session to maintain cleanliness.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating jsbi into a TypeScript project while adhering to strict mode

I have been developing a TypeScript library that relies on native BigInts. While it functions perfectly in Chrome, I encountered some issues with Safari. After some research, I stumbled upon the jsbi "polyfill" that seems to solve this problem. Unfortunat ...

java code for clicking all buttons with identical class

I have been attempting to select and click all buttons that share the same class. For instance: I am trying to select and click all buttons across the page with a specific class. I'm unsure if this is possible with the emulator or if there is a way to ...

Android 12 devices experiencing issues with Dialog cropping in Android applications

Our team has been encountering an issue with dialog clipping on certain devices, such as the Samsung TAB S7. Despite numerous attempts to resolve this problem consistently across all devices, we have not found a solution that works effectively. We have cre ...

Using jQuery to add and remove CSS classes on IE9 with Selenium

Hello, sorry for the generic question. We are currently automating our UI testing using Selenium Web Driver (v2.24.1) and everything is going smoothly except for IE9. One of the functionalities we are testing involves showing and hiding UI controls using ...

The outcome of the method is not being displayed

I have an issue with updating the value of an array method in an HTML file using the p tag. The problem is that even though the method returns the value, the HTML doesn't update to reflect the new value. Strangely, when using console.log, the value ap ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Swapping out an Array of Objects with a new Array in JavaScript

I am working with an Array of Items, each of which has a set of Properties. One specific property is called config: object[], which is an array of Objects. While I usually provide the complete object with the correct config array of objects, there are tim ...

The checkbox labeled "Shipping Same as Billing" is not functioning correctly. I have included my JavaScript code below, can someone please help me identify what I am overlooking? (Only JavaScript code is provided; HTML is

I'm having trouble transferring data from a 'shipping' address to the 'billing' address section. I've included all my code, but nothing seems to copy over when the check box useShip is selected. All the HTML code is provided f ...

I am experiencing issues with datejs not functioning properly on Chrome browser

I encountered an issue while trying to use datejs in Chrome as it doesn't seem to work properly. Is there a workaround for this problem if I still want to utilize this library? If not, can anyone recommend an excellent alternative date library that ...

Understanding the significance of the argument in the context of `express.json({ extended: false})`

Currently, I am in the process of setting up an API using express and encountered this particular line of code: app.use(express.json( { extended: false } )); Although I have referred to the documentation provided by express, I was unable to locate this sp ...

Steps to clear the form in vue after the ajax request has been successfully submitted

Exploring Vue.js Web Form Validation with a Scenario If you are interested in the vue-form validator library, it can be found at https://github.com/fergaldoyle/vue-form For a demonstration of this scenario, check out the following jsfiddle link: https:/ ...

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

The Jquery Load() function is causing [object object] to be returned instead of the element ID value when retrieving it

I am pulling a value from a MySQL query result in page.php and displaying it in display.html. I am successfully showing the value "VALUE368" in the div ID on display.html. However, I also want to log "VALUE386" in the Firebase Realtime Database. I am attem ...

Developing a Single Page Application using Express

I'm currently working on developing a SPA using the React/Redux/Express stack. The current state of my server setup is as follows: import express from 'express' import dotenv from 'dotenv' import path from 'path' dotenv ...

Can the text glow in the navbar be toggled?

Hey everyone, I'm new here and I've been struggling to find a solution to my issue. I have a website with a navigation bar that toggles different divs to simulate changing pages within the same HTML file. The problem is, there is no visual indica ...

Retrieve a value through an AJAX request when a button is clicked, even if the process is within a loop

$(document).ready(function() { $(".actdeact").on({ click: function() { var id = $('.getfromhere').text(); alert(id); {% for x in mylist %} <span class="getfromhere">{{x.id}}</span> < ...

Exploring the world of mathematics using JavaScript, adjusting the range input, and applying CSS transform with scale()

In my project, I have a container div set to a width of 794px and a range input with a maximum value of 250 and a minimum of 0. I am using CSS transform property like this: scale(1), where the scale is equivalent to 794px. The challenge arises when the br ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...