2015-11-04 53 views
0

我想使用一個csv文件來填充highcharts圖表,我將在java後端生成並使用spring mvc發送到結尾。春天MVC輸出CSV到highcharts

首先,我是幾乎可以肯定我的控制器類是問題,但我不知道如何正確地發送csv文件:

@Controller 
public class ChartController { 

    @RequestMapping(value = "/index", method = RequestMethod.GET) 
    public String indexHandler() { 
     return "index"; 
    } 

    @RequestMapping(value = "/out", method = GET) 
    public String chartHandler() { 
     String fileName = "test.csv" //note: I have also tried moving this 
            //file to my WEB-INF location and it doesn't make a difference 
     InputParser input = new InputParser(); 

     for (GenericDataObject gdo : input.getDataObjects()) { 
      CSVOutput.writeCSV(fileName,gdo); 
     } 

     return "index"; 
    } 

} 

我打算成功創建的CSV文件,因此這不是一個問題

這裏是我的highcharts

<html> 
<head> 
<script 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
<script src="http://code.highcharts.com/highcharts.js"></script> 
<script src="http://code.highcharts.com/modules/data.js"></script> 
<script src="http://code.highcharts.com/modules/exporting.js"></script> 

<some more high charts for font and color that I will leave out because its not currently being used> 

</head> 
<body> 

     <div id='container' style="width: 100%; height: 600px;"></div> 

     <script type="text/javascript"> 

     $(document)ready.function() { 
      var groupId = []; 
      var date = []; 
      var val = []; 
      var options = { 

      chart: { 
       renderTo: 'container', 
       type: 'line' 
       }, 
       title: { 
        text: 'test' 
       }, 
       xAxis: { 
       title: { 
        text: 'group and date' 
       }, 
       categories: [groupId, date] 
       }, 
       yAxis: { 
        title: { 
         text: 'data' 
        } 
       }, 
       series: [{ 
        data: val 
       }] 
      }; 

      $.get('http://localhost:8080/web-data-app/out', function(data)) { 
       alert("success"); 
       var lines = data.split('\n') 
       $.each(lines, function(lineNo, line) { 
        var items = line.split(','); 
        groupId.push(items[1]); 
        date.push(items[2]); 
        val.push(items[4]); 
        }); 
        var cahrt = new Highcharts.Chart(options); 
       }); 
      }); 
    </script> 
    </body> 
    </html> 

至於現在,我得到highcharts在我的容器的輪廓,以及成功的警報的Java腳本我知道很多工作。但是沒有數據顯示在圖表上。

回答

0

您可以使用httpResponse並將您的內容發送到那裏。像這樣

@RequestMapping(value = "/out", method = GET) 
public void chartHandler(HttpServletResponse httpResponse) { 
    String fileName = "test.csv" //note: I have also tried moving this 
           //file to my WEB-INF location and it doesn't make a difference 
    InputParser input = new InputParser(); 

    for (GenericDataObject gdo : input.getDataObjects()) { 
     CSVOutput.writeCSV(fileName,gdo); 
    } 
    httpResponse.setContentType("text/csv"); 
    //you can use the output stream below to pass your content 
    httpResponse.getOutputStream() 

}