Tips for parsing a JSON object from a servlet to a JSP page

As a newbie in the world of JSON and AJAX, I find myself struggling to create a chart using chart.js. I have a servlet that reads SQL statements and a JSP that processes these requests, but I lack experience in this type of programming. If anyone out there knows how to solve this problem, please lend me a hand. Even a small idea could point me in the right direction. Thank you.

ChartJsonDataServlet

public void dbConn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    final String DB_DRIVER = readConfig.getProperties("dbDriver");
    final String DB_URL = readConfig.getProperties("conUrl");
    final String USER = readConfig.getProperties("dbUser");
    final String PASSWORD = readConfig.getProperties("dbPass");

    try {
        Class.forName(DB_DRIVER);
     // loads driver
    Connection c = DriverManager.getConnection(DB_URL, USER, PASSWORD); // gets a new connection

    PreparedStatement ps = c.prepareStatement("SELECT m.month, IFNULL(x.sales, 0) AS sales FROM (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS sales FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month ORDER BY m.month ASC");
    ResultSet rs = ps.executeQuery();

    ArrayList<Integer> month = new ArrayList<Integer>();
    ArrayList<Integer> sales = new ArrayList<Integer>();
    while(rs.next())
    {
        month.add(rs.getInt("month"));
        sales.add(rs.getInt("sales"));         
    }
    String jmonth=new Gson().toJson(month);
    System.out.println("***sini***:-=1----------------------"+jmonth);
    String jsales=new Gson().toJson(sales);
    System.out.println("##sale## " +jsales);





         rs.close();
    return;
    }

chart.js

<!-- start: BAR CHART -->
                    <div class="container-fluid container-fullw bg-white">
                        <div class="row">
                            <div class="col-sm-12">
                                <h5 class="over-title margin-bottom-15">Bar <span class="text-bold">Chart</span></h5>
                                <div class="row">
                                    <div class="col-sm-6">
                                        <canvas id="barChart" class="full-width"></canvas>
                                    </div>
                                    <div class="col-sm-6">

                                        <p class="margin-top-20">
                                            <div id="barLegend" class="chart-legend"></div>
                                        </p>
                                        <span id="sana" ></span>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- end: BAR CHART -->
<script type="text/javascript">

    var Charts = function() {"use strict";
        var barChartHandler = function() {
            var options = {

                // Sets the chart to be responsive
                responsive: true,

                //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
                scaleBeginAtZero: true,

                //Boolean - Whether grid lines are shown across the chart
                scaleShowGridLines: true,

                //String - Colour of the grid lines
                scaleGridLineColor: "rgba(0,0,0,.05)",

                //Number - Width of the grid lines
                scaleGridLineWidth: 1,

                //Boolean - If there is a stroke on each bar
                barShowStroke: true,

                //Number - Pixel width of the bar stroke
                barStrokeWidth: 2,

                //Number - Spacing between each of the X value sets
                barValueSpacing: 5,

                //Number - Spacing between data sets within X values
                barDatasetSpacing: 1,

                //String - A legend template
                legendTemplate: '<ul class=\"name.toLowerCase()-legend\"> for (var i=0; i<datasets.length; i++){<li><span style="background-color:datasets[i].fillColor"></span>if(datasets[i].label){datasets[i].label%>}</li>}</ul>'
            };

            var dataarray = [65];
            dataarray.push(59);
            dataarray.push(27);

            var data = {
                labels: jmonth,
                datasets: [{
                    label: "My First dataset",
                    fillColor: "rgba(220,220,220,0.5)",
                    strokeColor: "rgba(220,220,220,0.8)",
                    highlightFill: "rgba(220,220,220,0.75)",
                    highlightStroke: "rgba(220,220,220,1)",
                    data: jsales
                }, ]
            };              

            // Get context with jQuery - using jQuery's .get() method.
            var ctx = $("#barChart").get(0).getContext("2d");
            // This will get the first returned node in the jQuery collection.
            var barChart = new Chart(ctx).Bar(data, options);
            ;
            //generate the legend
            var legend = barChart.generateLegend();
            //and append it to your page somewhere
            $('#barLegend').append(legend);
        };
        return {
            init: function() {  
                barChartHandler();

            }
        };
    }();
    </script>

If you have any insights on how to extract JSON data from the servlet into the JSP file, please share your wisdom with me. Your help would be greatly appreciated. Let's rock this programming challenge together!

Answer №1

To generate JSON, one can utilize the org.json.simple API or other options such as Jackson and GSON provided by Google. In this example, we will focus on using the org.json.simple API.

Suppose you have a servlet named ParseJSON.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.simple.JSONObject;

public class ParseJSON extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    
        response.setContentType("application/json");
        JSONObject obj = new JSONObject();
        
        obj.put("name", "Yoginth");
        obj.put("age", new Integer(19));
        obj.put("place", "Pollachi");
        PrintWriter out = response.getWriter();
        out.println("<h1>" + obj + "</h1>");
    }
}

If you view the output in a browser, it will display:

{"name": "Yoginth", "age": 19, "place": "Pollaci"}

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

Updating state from a React mapping component: A step-by-step guide

I am working on an API that needs data filtering and then I want to place the filtered data into a state export default class ModifyPage_Single extends React.Component { constructor(props) { super(props) this.state = {data:[],idd:" ...

Is it better to have a single object with all required modules in NodeJS, or follow the "standard" paths in the code?

Being a fan of creating global namespaces in javascript, I often use this approach in my app development. For instance, if my application is named Xyz, I typically create an object called XYZ to organize properties and nested objects like so: XYZ.Resource ...

Tips for creating <table> HTML code without relying on JSF tag libraries like h:datatable or ui:repeat, while still utilizing JSF for managing page navigation

I am facing a challenge with rendering tables in my application. The tables have 12 columns and up to 1800 rows, taking 8 seconds to display using h:dataTable in JSF. I attempted using ui:repeat with a Java List object in JSF for row data retrieval, which ...

Is it no longer possible to use v-for to iterate over translations in Nuxt 3 and @nuxtjs/i18n?

Imagine having an Array stored in our translations file en.js section: { title: 'This value is a string and it works perfectly', highlighted: [ { title: 'Highlighted title 1', text: 'Highlighted text ...

Tips on consolidating all settings into a single configuration file or distributing them across multiple configuration

It's been two years since I last used this. Now, I'm faced with the challenge of consolidating everything into one JSON file or if multiple JSON files are necessary. I am currently on version 11.9.46 and finding it difficult to navigate through ...

JSON variable unable to be stored in database

I have a Django application where I am attempting to save the configuration of a gridster widget as a JSON variable in the database. However, when I click the "Update" button on the webpage, no value is stored in the database. Below is my JavaScript code ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

NodeJS application does not acknowledge the term "Require"

I have completed the steps outlined on http://expressjs.com/en/starter/installing.html to set up my express NodeJS application. Following the installation, we navigated to the "myapp" directory and installed the "aws-iot-device-sdk" from https://github.com ...

In TypeScript, at what level should the timeout be specified?

I'm currently working on writing a debounce function in TypeScript, but I'm feeling uncertain about the type that should be assigned to a variable used with setTimeout. This is the snippet of my code: function debounced(func: () => void, wait ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Encountered an issue with decoding the JSON column in PySpark

Having trouble parsing a column of JSON data in my dataframe. The JSON seems to be malformed without key/value pairs. I attempted the following code: json_schema = spark.read.json(df.rdd.map(lambda row: row.data)).schema df = df.withColumn('p_data&apo ...

The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured. Currently, the regex /(\d+)(?=h ...

Creating a WordPress post popup using Ajax with SimpleModal and jQuery

I tried to follow the instructions provided in this tutorial but unfortunately, I couldn't get it to work. This is the process I followed: 1 / Including in the header <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ...

Converting JSON data from a URL into a Geodataframe

I have a task of extracting JSON data from a URL. My goal is to transform the data into a geodataframe format, especially dealing with nested attributes. It appears that the points are nested within lines in the dataset. The data source is: import urllib. ...

An error of type `TypeError`: attempting to call `[0,1]` as a function arises while using an IIFE

Check out the following code: var numberArray = [0, 1] (function() { numberArray.push(2) function nestedFunction() { numberArray.push(3) function anotherNestedFunction() { numberArray.push(4) } console.log(num ...

Jest - verifying the invocation of local storage within an async function that is currently being mocked

I need assistance with testing an API call within a React component. The current setup involves setting localStorage in the api call, which is causing issues when trying to test if it's being called correctly. login = () => { // <--- If I se ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

During an ajax request, the getter for <f:passThroughAttributes value> is not invoked during the RENDER RESPONSE phase

I am facing an issue where the method binding for the <f:passThroughAttributes> tag, which is used to populate components with passthrough attributes, is not being called during AJAX requests. <f:ajax execute="@this otherComponent" listen ...