【问题标题】:How to parse JSON object from servlet to jsp如何将 JSON 对象从 servlet 解析为 jsp
【发布时间】:2018-09-14 17:25:42
【问题描述】:

所以这是我第一次使用 JSON 和 AJAX。我需要使用 chart.js 制作图表。我有这个读取 sql 语句的 servlet,以及一个处理这些请求的 jsp。我事先没有任何经验编写这些类型的编程。请任何知道如何解决此问题的人帮助我。即使是一个小想法,也足以帮助我找到解决此问题的方法。谢谢。

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>

请帮助我如何将 json 数据从 servlet 捕获到 jsp 中。非常感谢你。程序员摇滚!

【问题讨论】:

    标签: javascript json ajax jsp


    【解决方案1】:

    您可以使用 org.json.simple API 创建 JSON,还有各种 API,例如 Google 提供的 Jackson GSON。所以这里我要去org.json.simple API

    让我们看看你有一个名为 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>");
       }
    }
    

    如果你在浏览器中签入它会这样写

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

    【讨论】:

    • 你知道如何在jsp中调用那个json数据吗?我被困在了这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多