簡體   English   中英

如何將哈希圖值從Java文件傳遞到Javascript

[英]How to Pass the hashmap value from a java file to Javascript

我正在嘗試使用Java File從數據庫中檢索值並將其存儲到HashMap。 請找到以下代碼(Sample.java):

import java.sql.*;
import java.util.HashMap;

public class Sample {

 static Connection conn;
 static PreparedStatement stmt;
 static ResultSet rs;
 String sql;
 static String project="Project1";
 public static HashMap< String, String> map = new HashMap< String, String>();
public static void main(String[] args) {

    try{  

        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
        stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
        stmt.setString(1,project);
        rs=stmt.executeQuery();
        while(rs.next())
        {
            System.out.println(rs.getString(1)+"  "+rs.getInt(2)+"  "+rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getInt(5));
        map.put("ProjectName", rs.getString(1));
        map.put("Total TestCase", String.valueOf(rs.getInt(2)));
        map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
        map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
        map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
        System.out.println("ProjectName  "+map.get("ProjectName"));

        }
        conn.close();
        }
    catch(Exception e)
        { System.out.println(e);}
}

}

請找到我從數據庫檢索到的以下數據:

ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted    
 Project1       50              30              8                20

我想將此值傳遞給Javascript,以便能夠使用這些值繪制圖表。 請在下面(test.html)找到我的HTML / Javascript代碼:

<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();
    str = stri.split(",");

        // How to call the value from java file so that I will be able to draw the below graph by passing the value.

    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>

請讓我知道如何進行操作,或者是否有人有其他示例。 請和我分享。 謝謝

  1. 您可以將地圖轉換為JSON 代替此HelloWorld類,您可以將其轉換為返回此JSON的服務。

     import java.sql.*; import java.util.HashMap; public class Sample { static Connection conn; static PreparedStatement stmt; static ResultSet rs; String sql; static String project = "Project1"; public static HashMap < String, String > map = new HashMap < String, String > (); //Notice how your main class is now converted into a service public static String getProjects() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue", "root", "root"); stmt = conn.prepareStatement("select * from TestCase where ProjectName= ?"); stmt.setString(1, project); rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1) + " " + rs.getInt(2) + " " + rs.getInt(3) + " " + rs.getInt(4) + " " + rs.getInt(5)); map.put("ProjectName", rs.getString(1)); map.put("Total TestCase", String.valueOf(rs.getInt(2))); map.put("TestCase Executed", String.valueOf(rs.getInt(3))); map.put("Failed TestCase", String.valueOf(rs.getInt(4))); map.put("TestCase Not Executed", String.valueOf(rs.getInt(5))); System.out.println("ProjectName " + map.get("ProjectName")); /*______________ NEW CODE ______________*/ JSONObject resultMap = new JSONObject(map); return resultMap.toString(); } } catch (Exception e) { System.out.println(e); } finally { conn.close(); } return ""; } } 
  2. 現在將您的test.html轉換為test.jsp並調用我們在上一步中創建的服務,然后將結果JSON輸出到javascript變量中。

    test.jsp

     <%@page import="com.path.to.Sample"%> <html> <head> <script> <!-- call that service and output that json into a javascript variable --> var resultantJSON = <%= Sample.getProjects() %> <!-- Now all that's left is to parse that json --> var projects = JSON.parse(resultantJSON); </script> </head> <body> ... ... </body> </html> 

    現在,從數據庫中獲取的所有結果都在Test.jsp projects變量中。 您可以像在jsp文件中的常規javascript對象一樣使用它們。

您必須使Java代碼可通過http訪問。 有幾種方法可以做到這一點。 您可以實現一個servlet,該servlet檢索http請求並可以將數據作為httpresponse發送回去。 搜索有關Java Servlet的教程,例如http://www.tutorialspoint.com/servlets/servlets-first-example.htm

您還可以使用Java Rest服務來提供信息。 搜索java rest教程,例如http://www.vogella.com/tutorials/REST/article.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM