如何将GSON值返回到javascript文件

How to return the GSON value to javascript file

本文关键字:javascript 文件 返回 GSON      更新时间:2023-09-26

我已经在java中编写了下面的代码来检索数据库中的值并存储在Json文件中。文件名为DatabaseGraphValue.java

package com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.GraphValue;
import com.google.gson.Gson;

@WebServlet("/GraphJsonValueServlet")
public class DataBaseGraphValue extends HttpServlet
{
static Connection conn = null;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";

public static Connection getDataBaseVale()
{
    if(conn != null)
    {
        return conn;
    }
    else
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
                         conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return conn;
    }

}

public DataBaseGraphValue()
{
    super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
    List<GraphValue> listOfGraphValue = getGraphValue();
    Gson gson = new Gson();
    String jsonString = gson.toJson(listOfGraphValue);
    response.setContentType("application/json");
    response.getWriter().write(jsonString);

}
private List<GraphValue> getGraphValue()
{
    conn = getDataBaseVale();
    List<GraphValue> listOfGraphValue = new ArrayList<GraphValue>();

    try 
    {
        stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
        stmt.setString(1,project);
        rs=stmt.executeQuery();
        while(rs.next())
        {
            GraphValue gv1 = new GraphValue();
            gv1.setProjectName(rs.getString(1));
            gv1.setTotalTestCase(rs.getInt(2));
            gv1.setTestCaseExecuted(rs.getInt(3));
            gv1.setFailedTestCase(rs.getInt(4));
            gv1.setTestCaseNotExecuted(rs.getInt(2));
            listOfGraphValue.add(gv1);
        }
    } 
    catch (SQLException e) 
    {
        e.printStackTrace();
    }

    return listOfGraphValue;
}
}

另一个文件名为GraphValue.java

package com;
public class GraphValue {
private String projectName;
private int totalTestCase;
private int testCaseExecuted;
private int failedTestCase;
private int testCaseNotExecuted;
public String getProjectName()
{
    return projectName;
}
public void setProjectName(String projectName)
{
    this.projectName =  projectName;
}
public int getTotalTestCase()
{
    return totalTestCase;
}
public void setTotalTestCase(int totalTestCase)
{
    this.totalTestCase =  totalTestCase;
}
public int getTestCaseExecuted()
{
    return testCaseExecuted;
}
public void setTestCaseExecuted(int testCaseExecuted)
{
    this.testCaseExecuted =  testCaseExecuted;
}
public int getFailedTestCase()
{
    return failedTestCase;
}
public void setFailedTestCase(int failedTestCase)
{
    this.failedTestCase =  failedTestCase;
}
public int getTestCaseNotExecuted()
{
    return testCaseNotExecuted;
}
public void setTestCaseNotExecuted(int testCaseNotExecuted)
{
    this.testCaseNotExecuted =  testCaseNotExecuted;
}
}

现在我需要帮助写一个JavaScript,这样我就可以访问我从数据库检索的值,并可以画一个图。下面是我的代码,我想要的Json数据。

<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "PieChart">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;"></div>
<p id="demo"></p>
<p id="demo1"></p>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 <script type="text/javascript">
 var row = [];
 var temp;
 var stri;
 google.load('visualization', '1.0', {'packages':['corechart']});
 google.setOnLoadCallback(getValues);
     function getValues() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        stri = xmlhttp.responseText;
            drawChart();
        }
    };
    xmlhttp.open("GET", "sample.java", true);
    xmlhttp.send();
    }
    function drawChart() 
    {
    var data = new google.visualization.DataTable();
     ----How to get the jason data here for the graph
    }
    data.addRows(row);
    var a = document.getElementById("ChartType").value;
    document.getElementById("demo1").innerHTML = "You selected: " + a;
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300
                   };
    var chart = new  google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
    chart.draw(data, options);
    }
</script>
</body>
</html>

值,我从数据库检索是:

 ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted    
 Project1       50              30              8                20

请告诉我下一步该怎么做。谢谢你

onreadystatechange处理程序中将xmlhttp.responseText传递给drawChart()

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  stri = xmlhttp.responseText;
  drawChart(stri);
}

at drawChart()

function drawChart(response) {
 var data = new google.visualization.DataTable();
 // How to get the jason data here for the graph
 // do stuff with `response`:`stri`
 console.log(response);
}