We will use a jersey to create a progress bar in struts. If you mistakenly landed here you may leave. If you are looking to create a progress bar in legacy applications, You are in the right place. You can implement the same in JSF as well JSP Application. I am writing it for the struts1 application as I was required in one of my projects.

What is Jersey

Jersey is an open-source framework for developing RESTful web services in Java. It is a reference implementation of the JAX-RS (Java API for RESTful Web Services) specification, which provides a standardized way to create RESTful APIs in Java.

Key features of the Jersey framework

  • Jersey allows developers to create RESTful web services using annotations, making it easy to define resources, methods, and parameters.
  •  In Jersey, resources are represented as resource classes that handle incoming HTTP requests and produce responses. These resource classes are annotated with JAX-RS annotations to define the mapping between HTTP methods and the corresponding Java methods.
  • Jersey provides support for handling HTTP requests and responses, including serialization and deserialization of Java objects to and from JSON or XML formats.
  • The Jersey supports dependency injection to inject dependencies into resource classes, such as services or other components needed for processing requests.
  • Jersey can be easily integrated with other Java frameworks, such as Spring, Hibernate, or JPA, to build more complex and feature-rich web applications.
  •  Jersey provides support for testing RESTful web services using testing frameworks like JUnit, making it easier to write and execute tests for API endpoints.
  • Overall, Jersey is a powerful framework for building RESTful web services in Java, providing developers with a flexible and efficient way to create APIs that follow the principles of REST architecture.

Download Jersey & Dependent Jars To Create Progress Bar In Struts

Below mentioned are dependencies of the Jersey framework

jakarta.activation.jar 
jakarta.activation-api.jar 
jakarta.annotation-api.jar 
jakarta.inject.jar 
jakarta.validation-api.jar 
jakarta.ws.rs-api.jar 
jakarta.xml.bind-api.jar 
jersey-client.jar 
jersey-common.jar 
jersey-container-servlet.jar 
jersey-container-servlet-core.jar 
jersey-media-jaxb.jar 
jersey-server.jar 
osgi-resource-locator.jar  

Configure Build Path To Add Required Jars To Create Progress Bar In Struts

Configuring the build path in a software development environment, such as Eclipse or IntelliJ IDEA, is essential for managing dependencies and ensuring that the project compiles correctly. Here is a general guide on how to configure the build path in Eclipse

1. Open Project Properties
– Right-click on the project in the Project Explorer.
– Select Properties from the context menu.
2. Access Build Path Settings
– In the Project Properties dialog, navigate to Java Build Path on the left-hand side.
3. Add External JARs or Libraries
– To add external JAR files or libraries to the build path, click on the Libraries tab.
– Click on the Add External JARs… button and browse to the location of the JAR files you want to add.
4. Add Project Dependencies
– If your project depends on other projects in the workspace, you can add them as dependencies:
– Click on the Projects tab.
– Click on the Add… button and select the projects you want to add as dependencies.
5. Configure Source Folders
– To specify the source folders containing your Java source code:
– Click on the Source tab.
– Here you can add or remove source folders if needed.
6. Order and Export
– The Order and Export tab allows you to specify the order in which libraries and projects are built and exported.
– This can be important when dealing with conflicting versions of libraries or when one library depends on another.
7. Apply Changes
– Click Apply or OK to save the project’s build path configuration.

By properly configuring the build path, you ensure that your project has access to all the necessary dependencies and resources required for compilation and execution. This helps in resolving compilation errors and running the application successfully.

Add Additional Servlet Mapping

Add new servlet mapping in the web.xml

What is web.xml?

`web.xml` is a deployment descriptor file used in Java web applications to configure settings for the web application. It is a standard XML file that is typically located in the `WEB-INF` directory of a web application.

What is Servlet Mapping?

Servlet mapping is a configuration in a Java web application that defines the association between a URL pattern and a servlet. Servlet mapping determines which servlet should handle requests that match a specific URL pattern.

When a client sends an HTTP request to a web application, the servlet container uses the servlet mapping configuration to determine which servlet should process the request. The servlet container looks at the URL of the request and matches it to the URL patterns defined in the servlet-mapping configuration.

<servlet> 
        <servlet-name>Rest</servlet-name> 
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
        <init-param> 
            <param-name>jersey.config.server.provider.packages</param-name> 
            <param-value>com.myorg.rest.controllers</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>Rest</servlet-name> 
        <url-pattern>/rest/v1/*</url-pattern> 
    </servlet-mapping> 

That is all, the configuration is done. Now we will create Rest Controllers and access them via the JSP Page to create progress bar in struts.

Components In Jersey

In Jersey, which is a popular framework for building RESTful web services in Java, components play a key role in defining and organizing different aspects of your application. Components in Jersey are used to configure and manage resources, providers, filters, and other components that make up your RESTful web service. We will use a component to create a progress bar in struts.

Several types of components can be defined in Jersey

1. Resources: Resources are the main building blocks of a RESTful web service in Jersey. They represent the endpoints or URIs that clients can interact with to perform CRUD operations on resources. Resources are typically annotated with `@Path` to specify the URI template for the resource.


2. Providers: Providers are components that handle different aspects of the request-response lifecycle in a Jersey application. This includes handling request and response serialization/deserialization, error handling, security, and more. Providers can be annotated with `@Provider` to be automatically registered with Jersey.


3. Filters: These Filters are components that allow you to intercept and manipulate HTTP requests and responses in a Jersey application. Filters can be used for tasks such as logging, authentication, authorization, and request/response modification. The Filters can be global filters that apply to all resources or resource-specific filters.


4. Context Resolvers: Context resolvers are components that provide custom serialization and deserialization logic for Java types in JAX-RS applications. Context resolvers can be used to customize how JAX-RS providers serialize/deserialize Java objects to/from JSON, XML, or other formats.

Create Rest Controller For Progress Bar In Struts Using Jersey

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.ws.rs.core.MediaType;
import java.ws.rs.core.Response;

@Path("/progress")
public class ProgressController {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getProgressBar() {
        ProgressModel progressModel = new ProgressModel();
        progressModel.setProcessName(Data.PROCESSNAME);
        progressModel.setTotalRecords(Data.TOTAL_RECORDS);
        progressModel.setUploadedRecords(Data.UPLOADED_VALIDATED_RECORDS);
        progressModel.setFileName(Data.FILE_NAME);
        return Response.ok(progressModel).build();
    }
}

note that ProgressModel and Data are DTO classes to set data

Now you may call it via JSP / JavaScript

<div id="progressional" class="modal">
    <!-- Modal content -->
    <div class="modal-content">
      <span class="close" id="close">&times;</span>
      <h3 id="title" style="display: flex; justify-content: center;"></h3>
      <div style="margin-left: 10px;">
        <label>File Name : </label> <label id="fileName"></label>
      </div>
      <div style="margin: 10px;">
        <label id="total label">Total Records : </label> <label id="total records">count</label>
      </div>
      <div style="margin: 10px;">
        <label>Processed Records : </label> <label id="processedRecords">count</label>
      </div>
      <div style="margin: 10px;">
        <label id="message"></label> <label id="message details"></label>
      </div>
    </div>
  </div>

JS to modify HTML elements Of Progress Bar In Struts.

$("#buttonId").click(function(){
    document.getElementById("progressModal").style.display = "block";
    document.getElementById("title").innerHTML = "Uploading";
    document.getElementById("close").style.visibility = "hidden";
    document.getElementById("totalRecords").style.visibility = "hidden";
    document.getElementById("totalLabel").style.visibility = "hidden";
    const i = setInterval(function() {
        let fetches = fetch("/context/rest/v1/progress");
        fetches.then(res =>
            res.json()).then(d => {     
                document.getElementById("totalRecords").innerHTML = d.totalRecords;
                document.getElementById("processedRecords").innerHTML = d.uploadedRecords;
                if (d.totalRecords > 0){
                    clear interval(i);
                    document.getElementById("progressModal").style.display = "none";
                }
                document.getElementById("fileName").innerHTML = d.fileName; 
                if (d.processName === 'error') {
                    clearInterval(i);
                    document.getElementById("message").innerHTML = "Error";
                    document.getElementById("messageDetails").innerHTML = d.processName;
                }
            })
        }, 1000);
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

I’m Sohail

A Java Developer focused on creating efficient, scalable solutions. With expertise in Java and backend development, I specialize in RESTful APIs, Struts1, Struts2, JSF, Hibernate, Spring, Jersey, Oracle ATG and clean, maintainable code. I’m driven by a love for problem-solving and continuous learning.

Let’s connect