简体   繁体   中英

Highcharts - From Servlet to JSP

I have some problems with Highcharts and servlet/jsp.

I'm not very familiar with AJAX and JQUERY.

I would like to display in a jsp page 2 real-time line series with the relevant data (x,y) loaded from a database through a java servlet.

This is the code inside my jsp:

<script type="text/javascript">
$(function () {

    var seriesOptions = [];
    $.getJSON('Grafico', function(data) {

        // Populate series
        for (i = 0; i < data.DeltaRealTime.length; i++){
            seriesOptions[i] = {
                name: data.DeltaRealTime[i].name,
                data: [data.DeltaRealTime[i].key, parseFloat(data.DeltaRealTime[i].value)]
            };
        }

        $('#container').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,

                events: {
                    load: function() {

                        // set up the updating of the chart each second
                        setInterval(function() {

                            $.getJSON('Grafico', function(data) {
                                // Populate series
                                for (i = 0; i < data.DeltaRealTime.length; i++){
                                    var chart = $('#container').highcharts();
                                    chart.series[i].addPoint([data.DeltaRealTime[i].key, parseFloat(data.DeltaRealTime[i].value)]);
                                }
                            });
                        }, 1000);
                    }
                }
            },
            title: {
                text: "Valori Delta"
            },
            xAxis: {
                title: {
                    text: 'Campione'
                }
            },
            yAxis: {
                labels: {
                    format: '{value:.1f}'
                },
                title: {
                    text: 'Delta(f)'
                },
            },
            series: seriesOptions
        });
    });
});
</script>

This is the "Grafico" servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/json");
    PrintWriter out = response.getWriter();

    try {

        HttpSession session = request.getSession();

        Seriale seriale = (Seriale)session.getAttribute("seriale");

        if(seriale == null)
            System.out.println("SERIALE=NULL");
        else {
            if(seriale.getSeriale().isOpen())
                System.out.println("SERIALE APERTA");

            System.out.println("ID SESSIONE DATI="+seriale.getSessioneDati().getId());
        }


        if(seriale != null && seriale.getSeriale().isOpen()) {

            System.out.println("INIZIO A LEGGERE I DATI DAL DB");

            Db db = new Db();
            db.apriConnessione();

            String sql = "SELECT * FROM MisuraRiposo ORDER BY id DESC LIMIT 1";
            PreparedStatement ps = db.getConnection().prepareStatement(sql);

            ResultSet rs = ps.executeQuery();

            Map<String, String> data1 = new HashMap<String,String>();
            Map<String, String> data2 = new HashMap<String,String>();

            if(rs.next()) {
                data1.put("name", "f1");
                data1.put("key", rs.getString("campione"));
                data1.put("value", rs.getString("f1"));
                data2.put("name", "f2");
                data2.put("key", rs.getString("campione"));
                data2.put("value", rs.getString("f2"));
            }

            rs.close();
            ps.close();
            db.chiudiConnessione();

            JSONObject json1 = new JSONObject(data1);
            JSONObject json2 = new JSONObject(data2);
            JSONArray array = new JSONArray();
            array.put(json1);
            array.put(json2);
            JSONObject finalObject = new JSONObject();
            finalObject.put("DeltaRealTime", array);

            out.write(finalObject.toString());
        }

    }
    catch(JSONException jse) {
        jse.printStackTrace();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    finally {
        out.flush();
        out.close();

        System.out.println("Fine servlet grafico");
    }

}

The problem is that I can't obtain the desired behaviour. I only obtain disconnected points.

Thanks in advance for any help :)

I managed to display in a jsp page 12 real-time line series with the relevant data (x,y) loaded from a database through a java servlet. The series are updated once a second. All works very well in Chrome and Firefox. Instead I'm experiencing problems with Internet Explorer 11.0.9600.17239 where the chart does not update (it remains on the first chart image forever). However, if I change to compatibility view (F12), the chart works very well also in Internet Explorer. I can't understand why. Can you help me? Sorry if the code is not very elegant.

This is the code inside my jsp:

<script type="text/javascript">
$(document).ready(function() {
//fare cose jQuery quando DOM è pronto
Highcharts.setOptions({
    global: {
        useUTC: false
    }
});

    var processed_json = [];
    $.getJSON('Grafico', function(data) {

        // draw chart
        $('#container').highcharts({
        chart: {
            zoomType: 'x',
            type: "spline",
            //animation: Highcharts.svg, // don't animate in old IE
            events: {
                load: function() {

                    // set up the updating of the chart each second
                    setInterval(function() {

                        $.getJSON('Grafico', function(data) {
                            // Populate series
                            for (i = 0; i < data.DeltaRealTime.length; i++){
                                var chart = $('#container').highcharts();
                                chart.series[i].addPoint([parseInt(data.DeltaRealTime[i].key),parseFloat(data.DeltaRealTime[i].value)]);
                            }
                        });
                    }, 1000);
                }
            }
        },
        title: {
            text: "Valori Delta"
        },
        xAxis: {
            title: {
                text: 'Campione'
            },
            labels: {
                step: 1
            }
        },
        yAxis: {
            labels: {
                format: '{value:.1f}'
            },
            title: {
                text: 'Delta(f)'
            }
        },
        series: [{
            name: 'f1',
            data: []
        }, {
            name: 'f2',
            data: []
        }, {
            name: 'f3',
            data: []
        }, {
            name: 'f4',
            data: []
        }, {
            name: 'f5',
            data: []
        }, {
            name: 'f6',
            data: []
        }, {
            name: 'f7',
            data: []
        }, {
            name: 'f8',
            data: []
        }, {
            name: 'f9',
            data: []
        }, {
            name: 'f10',
            data: []
        }, {
            name: 'f11',
            data: []
        }, {
            name: 'f12',
            data: []
        }]
    });
});

});

This is the "Grafico" servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    doPost(request, response);

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println("Avvio servlet grafico");

    Map<String, String> f1 = new HashMap<String,String>();
    Map<String, String> f2 = new HashMap<String,String>();
    Map<String, String> f3 = new HashMap<String,String>();
    Map<String, String> f4 = new HashMap<String,String>();
    Map<String, String> f5 = new HashMap<String,String>();
    Map<String, String> f6 = new HashMap<String,String>();
    Map<String, String> f7 = new HashMap<String,String>();
    Map<String, String> f8 = new HashMap<String,String>();
    Map<String, String> f9 = new HashMap<String,String>();
    Map<String, String> f10 = new HashMap<String,String>();
    Map<String, String> f11 = new HashMap<String,String>();
    Map<String, String> f12 = new HashMap<String,String>();

    response.setContentType("text/json");
    PrintWriter out = response.getWriter();

    try {

        HttpSession session = request.getSession();
        Seriale seriale = (Seriale)session.getAttribute("seriale");

        if(seriale == null)
            System.out.println("SERIALE=NULL");
        else {
            if(seriale.getSeriale().isOpen())
                System.out.println("SERIALE APERTA");

            System.out.println("ID SESSIONE DATI="+seriale.getSessioneDati().getId());
        }

        Delta delta = new Delta();

        if(seriale != null && seriale.getSeriale().isOpen() && seriale.getPrimaMisura() != null) {

            MisuraCampione primaMisura = new MisuraCampione(); 
            primaMisura = seriale.getPrimaMisura();
            System.out.println("***STAMPA PRIMA MISURA***");
            primaMisura.stampa();

            System.out.println("INIZIO A LEGGERE I DATI DAL DB");

            Db db = new Db();
            db.apriConnessione();

            String sql = "SELECT * FROM MisuraRiposo ORDER BY id DESC LIMIT 1";
            PreparedStatement ps = db.getConnection().prepareStatement(sql);

            System.out.println("QUERY=" + ps.toString());

            ResultSet rs = ps.executeQuery();

            if(rs.next()) {
                MisuraCampione misuraAttuale = new MisuraCampione();
                misuraAttuale.setCampione(rs.getInt("campione"));
                misuraAttuale.setF1(rs.getBigDecimal("f1"));
                misuraAttuale.setF2(rs.getBigDecimal("f2"));
                misuraAttuale.setF3(rs.getBigDecimal("f3"));
                misuraAttuale.setF4(rs.getBigDecimal("f4"));
                misuraAttuale.setF5(rs.getBigDecimal("f5"));
                misuraAttuale.setF6(rs.getBigDecimal("f6"));
                misuraAttuale.setF7(rs.getBigDecimal("f7"));
                misuraAttuale.setF8(rs.getBigDecimal("f8"));
                misuraAttuale.setF9(rs.getBigDecimal("f9"));
                misuraAttuale.setF10(rs.getBigDecimal("f10"));
                misuraAttuale.setF11(rs.getBigDecimal("f11"));
                misuraAttuale.setF12(rs.getBigDecimal("f12"));
                misuraAttuale.setT1(rs.getBigDecimal("t1"));
                misuraAttuale.setT2(rs.getBigDecimal("t2"));
                misuraAttuale.setTo(rs.getBigDecimal("to"));
                misuraAttuale.setFt(rs.getBigDecimal("ft"));
                misuraAttuale.setRh(rs.getBigDecimal("rh"));
System.out.println("***STAMPA MISURA ATTUALE***");
misuraAttuale.stampa();

                delta = delta.calcolaDelta(primaMisura, misuraAttuale);
System.out.println("***STAMPA DELTA***");
delta.stampa();
            }

            rs.close();
            ps.close();
            db.chiudiConnessione();

        }

        System.out.println("CAMPIONE="+delta.getCampione()+"-"+delta.getCampione2());
        System.out.println("F1="+delta.getF1());
        System.out.println("F2="+delta.getF2());

        f1.put("key", Integer.toString(delta.getCampione2()));
        f1.put("value", delta.getF1().toString());
        f2.put("key", Integer.toString(delta.getCampione2()));
        f2.put("value", delta.getF2().toString());
        f3.put("key", Integer.toString(delta.getCampione2()));
        f3.put("value", delta.getF3().toString());
        f4.put("key", Integer.toString(delta.getCampione2()));
        f4.put("value", delta.getF4().toString());
        f5.put("key", Integer.toString(delta.getCampione2()));
        f5.put("value", delta.getF5().toString());
        f6.put("key", Integer.toString(delta.getCampione2()));
        f6.put("value", delta.getF6().toString());
        f7.put("key", Integer.toString(delta.getCampione2()));
        f7.put("value", delta.getF7().toString());
        f8.put("key", Integer.toString(delta.getCampione2()));
        f8.put("value", delta.getF8().toString());
        f9.put("key", Integer.toString(delta.getCampione2()));
        f9.put("value", delta.getF9().toString());
        f10.put("key", Integer.toString(delta.getCampione2()));
        f10.put("value", delta.getF10().toString());
        f11.put("key", Integer.toString(delta.getCampione2()));
        f11.put("value", delta.getF11().toString());
        f12.put("key", Integer.toString(delta.getCampione2()));
        f12.put("value", delta.getF12().toString());

        JSONObject jsonF1 = new JSONObject(f1);
        JSONObject jsonF2 = new JSONObject(f2);
        JSONObject jsonF3 = new JSONObject(f3);
        JSONObject jsonF4 = new JSONObject(f4);
        JSONObject jsonF5 = new JSONObject(f5);
        JSONObject jsonF6 = new JSONObject(f6);
        JSONObject jsonF7 = new JSONObject(f7);
        JSONObject jsonF8 = new JSONObject(f8);
        JSONObject jsonF9 = new JSONObject(f9);
        JSONObject jsonF10 = new JSONObject(f10);
        JSONObject jsonF11 = new JSONObject(f11);
        JSONObject jsonF12 = new JSONObject(f12);

        JSONArray array = new JSONArray();
        if(delta.getCampione() > 0) {
            array.put(jsonF1);
            array.put(jsonF2);
            array.put(jsonF3);
            array.put(jsonF4);
            array.put(jsonF5);
            array.put(jsonF6);
            array.put(jsonF7);
            array.put(jsonF8);
            array.put(jsonF9);
            array.put(jsonF10);
            array.put(jsonF11);
            array.put(jsonF12);
        }

        JSONObject finalObject = new JSONObject();
        finalObject.put("DeltaRealTime", array);

System.out.println("FINALOBJECT=" + finalObject.toString());                
        out.write(finalObject.toString());

    }
    catch(SQLException sqle) {
        sqle.printStackTrace();
    }
    catch(JSONException jse) {
        jse.printStackTrace();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    finally {
        out.flush();
        out.close();

        System.out.println("Fine servlet grafico");
    }

}

The "Grafico" java servlet only returns to the jsp page the JSON encoded string used by Highcharts to display the 12 real-time series.

The JSON string passed to the jsp page is like this:

{"DeltaRealTime":[{"value":"0.1","key":"371"},{"value":"0.1","key":"371"},{"value":"0.0","key":"371"},{"value":"0.0","key":"371"},{"value":"0.0","key":"371"},{"value":"-0.1","key":"371"},{"value":"0.2","key":"371"},{"value":"0.3","key":"371"},{"value":"-0.2","key":"371"},{"value":"0.0","key":"371"},{"value":"0.0","key":"371"},{"value":"0.1","key":"371"}]}

Then, the javascript setInterval function updates once a second the graph by adding a new (x,y) point to each series through the function chart.series[i].addPoint([parseInt(data.DeltaRealTime[i].key),parseFloat(data.DeltaRealTime[i].value)]);

The new point is similar to the previous one:

{"DeltaRealTime":[{"value":"-0.1","key":"372"},{"value":"-0.1","key":"372"},{"value":"-0.1","key":"372"},{"value":"-0.2","key":"372"},{"value":"-0.2","key":"372"},{"value":"-0.4","key":"372"},{"value":"0.0","key":"372"},{"value":"0.1","key":"372"},{"value":"0.1","key":"372"},{"value":"-0.5","key":"372"},{"value":"-0.2","key":"372"},{"value":"-0.1","key":"372"}]}

I found the problem. It seems a JQUERY issue on Internet Explorer.

$.getJSON('Grafico', function(data) { ... }

doesn't work in IE11.

I changed it with

$.ajax({
                        type: $('#form1').attr('method'),
                        url: "Grafico",
                        cache:false,
                        dataType:'json',
                        success: function(data){
                            for (var i = 0; i < data.DeltaRealTime.length; i++){
                                chart1.series[i].addPoint([parseInt(data.DeltaRealTime[i].key),parseFloat(data.DeltaRealTime[i].value)]);
                            }
                        }
                    });

and all works very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM