Utilizing JavaScript to retrieve data from incoming Servlet requests

Currently, I am working on a web app using Java EE, following a specific pattern. The process involves sending a query to the database from a DAO pattern. Once the result of the query is obtained, it is passed to the controller (servlet), which in turn passes the results to the view, typically a JSP page.

So far, I have been utilizing Expression Language to manipulate data coming from the servlet. However, for creating statistics with a Google chart code, I now need to understand how to collect data using Javascript.

Let me provide you with some details:

This snippet shows the DAO portion, where we select ticket types and count them.

private static final String JPQL_SELECT_TICKETS_ETAT = "SELECT t.etat, COUNT(t.id_ticket) FROM Ticket t GROUP BY t.etat";

@PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager       em;


public List<Object[]> chargerTicketsParEtat() throws DAOException {
    List<Object[]> liste;
    TypedQuery<Object[]> query = em.createQuery(JPQL_SELECT_TICKETS_ETAT, Object[].class);
    try {
        liste = (List<Object[]>) query.getResultList();
    } catch ( NoResultException e ) {
        return null;
    } catch(Exception e) {
        throw new DAOException(e);
    }
    return liste;
}

The next code snippet belongs to the servlet:

        List<Object[]> lticket = ticketDao.chargerTicketsParEtat();
        String test= "this is a string";
        request.setAttribute("test", test);
        request.setAttribute("lticket",lticket);

And this is the relevant part of the JSP page:

The retrieved data is displayed in a table format like this:

<table>
<tr>
<th>Ticket State</th>
<th>Quantity</th>
</tr>
<c:forEach items="${lticket}" var="ticket">
<tr>
<td>${ticket[0]}</td>
<td>${ticket[1]}</td>
</tr>
</c:forEach>
</table>

Below is the sample Google chart code that I intend to use:

  <head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

  google.charts.load('current', {'packages':['corechart']});

  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>

I'm looking for guidance on how to fetch the lticket data so that I can incorporate it into the Google chart code effectively.

Answer №1

In my project, I tackled this issue by converting List<Object[]> lticket into JSON utilizing the Gson library and then transferring it to JSP through

request.setAttribute("lticketJson", json)
. To utilize this in your JSP, you can simply do
chart.draw(${lticketJson}, options);

Another approach would be to create a REST endpoint using JAX-RS capabilities that only serves JSON data and then consume this result using JavaScript's fetch() method or something similar.

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

Struggles encountered while styling time on a React countdown timer created using hooks

Looking to create a basic countdown timer with minutes and seconds, along with a reload button to reset it if needed. However, I'm facing an issue with parsing the time in the correct format. You can check out a live preview of my progress here: https ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...

What methods can be used to defer the visibility of a block in HTML?

Is there a way to reveal a block of text (h4) after a delay once the page has finished loading? Would it be necessary to utilize setTimeout for this purpose? ...

What is the best way to initiate animation on a child element once the parent element has reached 75% completion of its animation

Is there a way to use JavaScript to determine when an animation is 75% complete? I have many nested HTML elements that need to be animated with an animation delay property, where the nested animation should start when the parent element is 75% complete. I ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

Looping through a Vue Bootstrap modal using a v-for directive

I am working on a Vue Bootstrap modal placed within a v-for loop. I need to replace the '1' in both 'v-b-modal.modal-1' and 'modal-1' with the index value, which I can access as {{ index }} while looping through the items. How ...

Performing subtraction operation on a selected floating-point value from a database using PHP

I am facing an issue with my code where I need to subtract a float value selected from the database and update the subtracted values in the database table. Below is my code snippet: $AmountGiven = $_POST['AmountGiven']; $conn = mysqli_connect("l ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

The subsequent page fails to load. Issue with the pagination feature

I'm currently stuck trying to implement pagination in my task and it's not functioning as expected. My approach involved creating two buttons with click events attached, along with a data property that changes when the buttons are clicked. This ...

Comprehending the Syntax of the ExtJS Framework

I have recently inherited a project utilizing Sencha's ExtJS framework without any handover or documentation. As I navigate through the code, I find myself trying to decipher certain syntax and exploring resources tailored for newcomers to this specif ...

"Troubleshooting the issue of Angular UI-Select failing to display a large

Check out my comprehensive json file containing cities from around the world: download here. Furthermore, take a look at the snippet of html code below: <div class="form-group"> <label class="control-label"> CITY </label> ...

To customize or not to customize?

Lately, there has been a growing trend of people incorporating custom attributes into their HTML tags to add extra data for use in JavaScript code. I'm curious to hear thoughts on the practice of using custom attributes and what alternatives are avai ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...

Using Node.js to send instructions to an HTTP server in order to highlight or add color to specific elements within

I have set up a server that receives data from a gaze sensor, as well as an HTTP server that serves an HTML page. I am looking for a way to dynamically highlight elements in the HTML based on the incoming data. Any suggestions on what resources or techniqu ...

When I changed the encoding of a live texture to sRGB in Three.js, the frame rate dropped by fifty percent

I am currently working on a threejs application that requires updating a texture in each frame. The output encoding of the THREE.WebGLRenderer is set to sRGB. Upon setting the texture encoding to sRGB, I observed that the rendering result is accurate. How ...

Stop the submission of MVC Form

Using AJAX, I have a form with fields in a partial view that is sent to a controller action when submitted. The partial view appears in a pop-up div when a button on the main form is clicked. If the user completes and submits the form, the update is succes ...

Unable to pass an event parameter using my this.handleChange function in react-native

Encountering an issue with the error message "undefined is not an object (evaluating 'event.preventDefault)" It appears that I am unable to pass an event parameter to the handleChange function in my child component, which is being rendered in the par ...

Develop a seamless user experience by creating dynamic forms using Jquery, PHP, and

I have been attempting to create a simple contact form using jQuery, AJAX, and PHP without refreshing the page. Everything seems to be working smoothly except for event.preventDefault(); Here are my files: Contact_engine.php <?php $name = $_POST ...