文章出處

 

很多時候圖表展現的數據都是從服務器端獲取,現在來做一個簡單的異步獲取json數據的例子。

服務器端用Servlet3.0實現,JSP頁面通過jquery異步請求json數據提供給Highcharts展現。

  1、用一個實體類封裝要展現的信息

 
package cn.luxh.app.entity;

/**
 * 瀏覽器市場份額
 * @author Luxh
 * 2012-11-3
 */
public class BrowserShare {
    
    //瀏覽器名稱
    private String name;
    //份額
    private float share;
    
    public BrowserShare(String name, float share) {
        super();
        this.name = name;
        this.share = share;
    }
    
    public float getShare() {
        return share;
    }

    public void setShare(float share) {
        this.share = share;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    
    

}
 

  2、處理請求的Servlet

 
package cn.luxh.app.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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.google.gson.Gson;

import cn.luxh.app.entity.BrowserShare;

@WebServlet(name="dataServlet",value="/servlet/dataServlet")
public class DataServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        List<BrowserShare> resultList = getData();
        Gson gson = new Gson();
        String result = gson.toJson(resultList);//轉成json數據   
        
        PrintWriter out = response.getWriter();
        out.write(result);
        out.flush();
        out.close();
    }
    
    /**
     * 獲取數據
     */
    private List<BrowserShare> getData() {
        
        List<BrowserShare> resultList = new ArrayList<BrowserShare>();
        resultList.add(new BrowserShare("Chrome",18.55F));
        resultList.add(new BrowserShare("Firefoc",19.99F));
        resultList.add(new BrowserShare("IE",54.13F));
        resultList.add(new BrowserShare("Oher",0.49F));
        resultList.add(new BrowserShare("Oprea",1.63F));
        resultList.add(new BrowserShare("Safari",5.21F));
        return resultList;
    }


}
 

  3、JSP頁面

 
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highcharts Example</title>
        <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.2.min.js"></script>
        <script src="${pageContext.request.contextPath}/js/highcharts.js"></script>
        <script src="${pageContext.request.contextPath}/js/modules/exporting.js"></script> 
        <script type="text/javascript">
            $(function () {
                var chart;
                $(document).ready(function() {
                    chart = new Highcharts.Chart({
                        //常規圖表選項設置
                        chart: {
                            renderTo: 'container',        //在哪個區域呈現,對應HTML中的一個元素ID
                            plotBackgroundColor: null,    //繪圖區的背景顏色
                            plotBorderWidth: null,        //繪圖區邊框寬度
                            plotShadow: false            //繪圖區是否顯示陰影            
                        },
                        
                        //圖表的主標題
                        title: {
                            text: '2012年10月份瀏覽器市場份額'
                        },
                        //當鼠標經過時的提示設置
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage}%</b>',
                            percentageDecimals: 1
                        },
                        //每種圖表類型屬性設置
                        plotOptions: {
                            //餅狀圖
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    color: '#000000',
                                    connectorColor: '#000000',
                                    formatter: function() {
                                        //Highcharts.numberFormat(this.percentage,2)格式化數字,保留2位精度
                                        return '<b>'+ this.point.name +'</b>: '+Highcharts.numberFormat(this.percentage,2) +' %';
                                    }
                                }
                            }
                        },
                           //圖表要展現的數據
                        series: [{
                            type: 'pie',
                            name: '市場份額'
                        }]
                    });
                });
                
                //異步請求數據
                $.ajax({
                    type:"GET",
                    url:'${pageContext.request.contextPath}/servlet/dataServlet',//提供數據的Servlet
                    success:function(data){
                        //定義一個數組
                        browsers = [],
                        //迭代,把異步獲取的數據放到數組中
                        $.each(data,function(i,d){
                            browsers.push([d.name,d.share]);
                        });
                        //設置數據
                        chart.series[0].setData(browsers);  
                    },
                    error:function(e){
                        alert(e);
                    }
                });
                
                
            });
        </script>
    </head>
    <body>
    
    <!--  圖表的呈現區域,和常規圖表選項設置中的renderTo: 'container'對應-->
    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>

    </body>
</html>
 

  4、展現的結果

 

 

 

 

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()