使用谷歌图表生成动态统计数据

时间:2017-05-19 00:49:14

标签: javascript model-view-controller graph google-chartwrapper

我想知道是否可以使用谷歌图表制作简单动态的图表;这里我实际使用的是:

Oracle DB,JSTL,EL,JSP页面。

为了实现上述结果,在我的知识范围内还应该有什么。

修改

我将通过JPQL从ORACLE数据库中收集数据,它们将存储在包含每个行的名称和编号的Object []列表中,它们将通过servlet发送到JSP页面:{ {1}} 如何从JSP访问此列表以及如何将它们存储在生成图表的javascript代码中。

编辑:添加详细信息

这是DAO部分,选择门票类型并计算它们。

request.setAttribute("data",listemployees);

下一个代码发生在servlet中:

private static final String JPQL_SELECT_TICKETS_ETAT = "SELECT t.etat, COUNT(t.id_ticket) FROM Ticket t GROUP BY t.etat";

@PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager       em;


public List<Object[]> chargerTicketsParEtat() throws DAOException {
    List<Object[]> liste;
    //List<Object[]> results = em.createQuery("").getResultList();
    TypedQuery<Object[]> query = em.createQuery(JPQL_SELECT_TICKETS_ETAT, Object[].class);
    //query.setParameter(PARAM_TICKET, id_ticket);
    try {
        liste = (List<Object[]>) query.getResultList();
    } catch ( NoResultException e ) {
        return null;
    } catch(Exception e) {
        throw new DAOException(e);
    }
    return liste;
}

这是JSP页面:

结果在这样的表格中以数字表示:

        List<Object[]> lticket = ticketDao.chargerTicketsParEtat();
        String test= "this is a string";
        request.setAttribute("test", test);
        request.setAttribute("lticket",lticket);

这就是我要使用的那种哈特:

<table>
<tr>
<th>Etat ticket</th>
<th>Nombre</th>
</tr>
<c:forEach items="${lticket}" var="ticket">
<tr>
<td>${ticket[0]}</td>
<td>${ticket[1]}</td>
</tr>
</c:forEach>
</table>

它被置于头脑中,我想知道我应该用什么语言将表格中表示的数据注入到图表的脚本中,我所知道的就是EL (表达式langugae)不能放在脚本中,因为它在服务器部分解释,而js由浏览器解释 新服务器:`

  <head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

  // Load the Visualization API and the corechart package.
  google.charts.load('current', {'packages':['corechart']});

  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    // Set chart options
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>

JSP PAGE:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");


        List<Object[]> lticket = ticketDao.chargerTicketsParEtat();


        PrintWriter out = response.getWriter();

        JSONObject json = new JSONObject();
        try{

            json.put("status", 200);
            json.put("msg", "OK");  

            JSONObject map = new JSONObject();
            String nom="Non défini";
            long valeur;
            for (Object[] result : lticket) {

                if((int)result[0]==1)
                    nom="En attente de prise en charge";
                else if((int)result[0]==2)
                    nom="En attente de validation";
                else if((int)result[0]==3)
                    nom="Cloturé";
                else if((int)result[0]==4)
                    nom="En cours de traitement";
                valeur = (long) result[1];
                map.put(nom,valeur);
            }
            json.put("map", map);

        }catch(JSONException e){
            e.printStackTrace();
        }
        out.print(json.toString());
        request.setAttribute("lticket", lticket);
        this.getServletContext().getRequestDispatcher("/NewFile2.jsp").forward(request, response);

    }

`

1 个答案:

答案 0 :(得分:1)

对于DAO部分,您不需要更改任何内容。

对于servlet,你需要像这样返回一个json:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class ChartsDataServlet extends HttpServlet {

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

        response.setContentType("application/json");
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        JSONObject json = new JSONObject();
        try{

            json.put("status", 200);
            json.put("msg", "OK");  

            JSONObject map = new JSONObject();

            map.put("Mushrooms", 3);
            map.put("Onions", 1);
            map.put("Olives", 1);
            map.put("Zucchini", 1);
            map.put("Pepperoni", 2);
            json.put("map", map);

        }catch(JSONException e){
            e.printStackTrace();
        }
        out.print(json.toString());
    }
}

然后在要绘制图表的页面上使用此servlet-url(比如chartsDataUrl)。

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">
       var jsonData = [];
       $(document).ready(function(){
           $.ajax({url: "/chartsDataUrl", success: function(result){
               jsonData = result.map;
           }});
       });


      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        for (var key in jsonData) {
          data.addRow([key,jsonData[key]]);
         }

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

如果您有任何疑问,请与我们联系。