2

So this is my first time using JSON and AJAX. I am required to make chart using chart.js. I had this servlet that read sql statement, and a jsp that process these request. I don't have any experience beforehand writing these type of programming. Please anyone who knows how to solve this please help me. Even it's a little idea it should be enough to help me find a way to solve this. 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 {
            //main function to initiate template pages
            init: function() {  
                barChartHandler();

            }
        };
    }();
    </script>

Please help me how to capture json data from the servlet into the jsp. Big thanks to you. Programmer rocks!

Mace
  • 105
  • 2
  • 17

1 Answers1

0

You Can use org.json.simple API to create JSON there are various API too like Jackson GSON which has provided from Google. so here I am going to org.json.simple API

Let’s see you have the servlet named with 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 check in browser it will be written like

{"name": "Yoginth", "age":19, "place":"Pollaci"}
Yogi
  • 609
  • 1
  • 8
  • 21