admin管理员组

文章数量:1426003

I have a .java class to read a mongodb collection and copy the contents into the .json file.

.json file is then provided to the chart (created using Fusion Charts as it only accepts data either in json format or in xml format) written in javascripts in html and then the chart is build on the basis of the data provided to the chart.

My requirement is to call a java class from java script so that it will get the data in .json file and chart would get created based on it.

How to do so?

    public class Write {

    //@SuppressWarnings("null")
    public void connect() throws Exception{

        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        DB db = mongo.getDB("Age");
        DBCollection collection = db.getCollection("agegroup");



        try{

                File file = null;
                String content = "{ "+
      "  \"chart\": { \n"+ 

          "      \"caption\" : \"Weekly Sales Summary\" ,\n"+
           "  \"xAxisName\" : \"Week\",\n" +
              "  \"yAxisName\" : \"Sales\",\n"+
             " \"numberPrefix\" : \"$\" \n"+
        "},\n"+

         "\"data\":[\n";

                // if file doesnt exists, then create it
                file = new File("C:/Users/ila/Desktop/pie.json");


                file.createNewFile();


                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);

                DBObject s;


                String str;
                String delimiter=",";

                DBCursor cursorDoc = collection.find();
                while (cursorDoc.hasNext()) {
                    s=cursorDoc.next();

                     str=s.toString();
                     String[] str1= str.split(delimiter);

                            bw.write("{\n");
                            bw.write(str1[1]+", \n");
                            bw.write(str1[2]+"\n");

                            if(cursorDoc.hasNext())
                            bw.write(",");

                            System.out.println(Arrays.toString(str1));
                }

                bw.write("]\n");
                bw.write("}\n");

                bw.close();

                System.out.println("Done");

          }catch(Exception e){
             e.printStackTrace();
          }

    }
}

.html code

    <!DOCTYPE html>
<html>
<head>
<title>Pie chart</title>
<script type="text/javascript" src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.charts.js"></script>
<script type="text/javascript" src="fusioncharts/themes/fusioncharts.theme.zune.js"></script>

<script type="text/javascript">

FusionCharts.ready(function(){

    var revenueChart = new FusionCharts({
     //type: "pie2d",
     type: "pie2d",
      renderAt: "chart-container",
      width: "430",
      height: "450",
      dataFormat: "json",

   events: {
       'slicingStart': function(evtObj, argObj){
           var label = argObj.data.categoryLabel;
          //  alert(label);
            var n= label.localeCompare("Teenage")
            if(n==0)
                {
                   alert("An alert Msg!!!Teenage");
                 //  document.getElementById('iframe1').contentWindow.location.reload();


                 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }
          //  document.getElementById("iframe_a").contentDocument.location.reload(true);

          var m= label.localeCompare("Child")
             if(m==0)
                {
                   alert("An alert Msg!!!Child");
 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }

          var l= label.localeCompare("Adult")
             if(l==0)
            {
               alert("An alert Msg!!!Adult");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }

          var p= label.localeCompare("Senior")
             if(p==0)
            {
               alert("An alert Msg!!!Senior");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }
       }
       }
  });
  revenueChart.setJSONUrl("pie.json");
 //  revenueChart.setJSONData("C:/data/db/Age.json");
     revenueChart.render("chart-container");
   }
);


</script>

</head>
<body>
<div id="chart-container"  > </div>


</body>
</html>

I have a .java class to read a mongodb collection and copy the contents into the .json file.

.json file is then provided to the chart (created using Fusion Charts as it only accepts data either in json format or in xml format) written in javascripts in html and then the chart is build on the basis of the data provided to the chart.

My requirement is to call a java class from java script so that it will get the data in .json file and chart would get created based on it.

How to do so?

    public class Write {

    //@SuppressWarnings("null")
    public void connect() throws Exception{

        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        DB db = mongo.getDB("Age");
        DBCollection collection = db.getCollection("agegroup");



        try{

                File file = null;
                String content = "{ "+
      "  \"chart\": { \n"+ 

          "      \"caption\" : \"Weekly Sales Summary\" ,\n"+
           "  \"xAxisName\" : \"Week\",\n" +
              "  \"yAxisName\" : \"Sales\",\n"+
             " \"numberPrefix\" : \"$\" \n"+
        "},\n"+

         "\"data\":[\n";

                // if file doesnt exists, then create it
                file = new File("C:/Users/ila/Desktop/pie.json");


                file.createNewFile();


                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);

                DBObject s;


                String str;
                String delimiter=",";

                DBCursor cursorDoc = collection.find();
                while (cursorDoc.hasNext()) {
                    s=cursorDoc.next();

                     str=s.toString();
                     String[] str1= str.split(delimiter);

                            bw.write("{\n");
                            bw.write(str1[1]+", \n");
                            bw.write(str1[2]+"\n");

                            if(cursorDoc.hasNext())
                            bw.write(",");

                            System.out.println(Arrays.toString(str1));
                }

                bw.write("]\n");
                bw.write("}\n");

                bw.close();

                System.out.println("Done");

          }catch(Exception e){
             e.printStackTrace();
          }

    }
}

.html code

    <!DOCTYPE html>
<html>
<head>
<title>Pie chart</title>
<script type="text/javascript" src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.charts.js"></script>
<script type="text/javascript" src="fusioncharts/themes/fusioncharts.theme.zune.js"></script>

<script type="text/javascript">

FusionCharts.ready(function(){

    var revenueChart = new FusionCharts({
     //type: "pie2d",
     type: "pie2d",
      renderAt: "chart-container",
      width: "430",
      height: "450",
      dataFormat: "json",

   events: {
       'slicingStart': function(evtObj, argObj){
           var label = argObj.data.categoryLabel;
          //  alert(label);
            var n= label.localeCompare("Teenage")
            if(n==0)
                {
                   alert("An alert Msg!!!Teenage");
                 //  document.getElementById('iframe1').contentWindow.location.reload();


                 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }
          //  document.getElementById("iframe_a").contentDocument.location.reload(true);

          var m= label.localeCompare("Child")
             if(m==0)
                {
                   alert("An alert Msg!!!Child");
 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }

          var l= label.localeCompare("Adult")
             if(l==0)
            {
               alert("An alert Msg!!!Adult");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }

          var p= label.localeCompare("Senior")
             if(p==0)
            {
               alert("An alert Msg!!!Senior");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }
       }
       }
  });
  revenueChart.setJSONUrl("pie.json");
 //  revenueChart.setJSONData("C:/data/db/Age.json");
     revenueChart.render("chart-container");
   }
);


</script>

</head>
<body>
<div id="chart-container"  > </div>


</body>
</html>
Share Improve this question edited Apr 22, 2015 at 6:08 Root 2,3475 gold badges30 silver badges59 bronze badges asked Apr 22, 2015 at 5:56 ila mahajanila mahajan 311 gold badge1 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

Convert your Java Class into Servlet and using Ajax hit the servlet and do the required tasks. look into this link for a starter.

You can either use a servet engine like tomcat, and write a servlet that will serve your JSON document, or use the .sun.httpserver.* classes that is in the JRE.

Here you can take the use of REST client and ajax call in order to connect with the java class without the page refresh

For example let it be your ajax call.

$.ajax(
    {   url: 'in/your_class_name/path_name',
        type : 'POST',
        dataType: 'json',
        success : function (data) {
          //your script code
        },
        error:function(data,status,er) {
        alert("Error Loading Section Data: "+data);
    }
});

And then you need to configure your web.xml file as follows

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3/2001/XMLSchema-instance" xmlns="http://java.sun./xml/ns/javaee" xmlns:web="http://java.sun./xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun./xml/ns/javaee http://java.sun./xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Application Name</display-name>

      <context-param>
            <param-name>resteasy.servlet.mapping.prefix</param-name>
            <param-value>/in/</param-value>
      </context-param>

      <context-param>
            <param-name>resteasy.scan</param-name>
            <param-value>true</param-value>
      </context-param>

      <listener>
            <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
      </listener>

      <filter>
            <filter-name>Resteasy</filter-name>
            <filter-class>org.jboss.resteasy.plugins.server.servlet.FilterDispatcher</filter-class>
      </filter>

      <filter-mapping>
            <filter-name>Resteasy</filter-name>
            <url-pattern>/in/*</url-pattern>
      </filter-mapping>

      <wele-file-list>
        <wele-file>index.html</wele-file>    
      </wele-file-list>

</web-app>

This is for jboss server for apache similar , and this configuarion you can google easily

Next is setting the class. In the java class the actions and class selections are controlled by annotation please look at the example below.

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.mons.beanutils.BeanUtils;

@Path("/your_class_name")
public class Write {

    @Context
    HttpServletResponse res;

    @SuppressWarnings("unchecked")
    @POST
    @Produces("application/json")
    @Path("/path_name")
    public String your_function(@Context HttpServletRequest request )throws IOException{

        //your code
        return "succcess";
    }
}

Here your_class_name and path_name are the alternative names you are giving for access

And finally you need to download the jar file from the flowing link and add in your library

http://www.java2s./Code/Jar/c/Downloadmonsbeanutils183jar.htm

本文标签: Calling java class from javascript written in htmlStack Overflow