1

I am trying to retrieve the value from DataBase using Java File and storing it to HashMap. Please find the below code (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);}
}

}

Please find the below data which I am retrieving from the databse:

ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted    
 Project1       50              30              8                20

I want to pass this value to Javascript and so that I am able to draw a chart using these values. Please find my HTML/Javascript code below (test.html):

<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>

Please let me know how to proceed or if anyone have any other example. Please share it with me. Thank you

2 Answers 2

4
  1. You can convert your map to JSON. Instead of this HelloWorld class, you can convert it into a service that returns this `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. Now convert your test.html to test.jsp and call that service that we've created in previous step and output the resultant JSON into a javascript variable.

    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>
    

    Now all your results that you fetched from your database are in projects variable in Test.jsp. You can use them like conventional javascript object in your jsp file.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to make the Java code accessable via http. There are several ways to do this. You can implement a servlet which retrieves the http request and can send data back as httpresponse. Search for a tutorial on java servlet, e.g. like this http://www.tutorialspoint.com/servlets/servlets-first-example.htm

You could also use a java rest service to supply the information. Search for java rest tutorial, e.g. like this http://www.vogella.com/tutorials/REST/article.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.