如何从servlet解析JSON对象到jsp

时间:2022-07-12 11:59:39

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.

这是我第一次使用JSON和AJAX。我被要求用chart.js制作图表。我有一个读取sql语句的servlet和一个处理这些请求的jsp。我以前没有编写这类程序的经验。谁知道怎么解决这个问题,请帮帮我。即使是一个小小的想法也足以帮助我找到解决这个问题的方法。谢谢你!

ChartJsonDataServlet

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

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!

请帮助我如何从servlet捕获json数据到jsp中。大的谢谢你。程序员的岩石!

1 个解决方案

#1


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

您可以使用org.json。创建JSON的简单API有各种各样的API,比如从谷歌提供的Jackson GSON。这里是org。json。简单的API

Let’s see you have the servlet named with ParseJSON.java

让我们看看您使用ParseJSON.java命名的servlet

    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"}

#1


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

您可以使用org.json。创建JSON的简单API有各种各样的API,比如从谷歌提供的Jackson GSON。这里是org。json。简单的API

Let’s see you have the servlet named with ParseJSON.java

让我们看看您使用ParseJSON.java命名的servlet

    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"}