Spring MVC与EChart绘制图表(一)

两盒软妹~` 提交于 2019-12-24 15:22:55

工具:IDEA IntelliJ 2018,MySQL

框架:Spring MVC、MyBatis

流程

步骤1:客户访问系统提供的地址,从而访问控制器

步骤2:获取页面视图(.jsp)

步骤3:返回视图,同时在jsp中通过ajax调用数据接口

步骤4:获取数据库数据

步骤5:通过返回的数据渲染视图

前期准备:echarts-all.js、jquery.min.js、数据sql(资源下载:https://download.csdn.net/download/m_sophia/12035627)

代码

1、请求响应封装

public class EChartData {

    public List<String> legend = new ArrayList<String>();// 数据分组
    public List<String> category = new ArrayList<String>();// 横坐标
    public List<Series> series = new ArrayList<Series>();// 纵坐标
    public List<String> color = new ArrayList<String>();// 颜色

    public EChartData(List<String> legendList, List<String> categoryList,
                      List<Series> seriesList,List<String> colorList) {
        super();
        this.legend = legendList;
        this.category = categoryList;
        this.series = seriesList;
        this.color = colorList;
    }
}

2、数据封装

public class Series<T> {
    public String name;

    public String type;
    public List<T> data;

    public Series(String name, String type, List<T> data) {
        super();
        this.name = name;
        this.type = type;
        this.data = data;
    }
}

3、颜色设置

public class ChartUtil {

    private static final Color[] COLORS = new Color[]{Color.RED, Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA,
            Color.ORANGE, Color.PINK, Color.YELLOW, Color.BLACK, Color.GRAY, Color.LIGHT_GRAY};

    public static String toHexFromColor(Color color) {
        String r, g, b;
        StringBuilder su = new StringBuilder();
        r = Integer.toHexString(color.getRed());
        g = Integer.toHexString(color.getGreen());
        b = Integer.toHexString(color.getBlue());
        r = r.length() == 1 ? "0" + r : r;
        g = g.length() == 1 ? "0" + g : g;
        b = b.length() == 1 ? "0" + b : b;
        r = r.toUpperCase();
        g = g.toUpperCase();
        b = b.toUpperCase();
        su.append("#");
        su.append(r);
        su.append(g);
        su.append(b);
        return su.toString();
    }

    /**
     * 字符串转换成Color对象
     *
     * @param colorStr 16进制颜色字符串
     * @return Color对象
     */
    public static Color toColorFromString(String colorStr) {
        colorStr = colorStr.substring(4);
        Color color = new Color(Integer.parseInt(colorStr, 16));
        //java.awt.Color[r=0,g=0,b=255]
        return color;
    }

    /**
     * 选择分组的颜色
     *
     * @param size
     * @return
     */
    public static String[] getColorList(int size) {
        String[] colorArrays = new String[size];
        for (int i = 0; i < size; i++) {
            colorArrays[i] = toHexFromColor(COLORS[i]);
        }
        return colorArrays;
    }
}

4、Controller

@Controller
@RequestMapping("/chart")
public class FruitController {

    @Autowired
    private FruitService fruitService;

    @RequestMapping("/bar")
    public ModelAndView barChartView(ModelAndView mv) {
        mv.setViewName("BarChart");
        return mv;
    }

    @RequestMapping("/showEChartBar")
    @ResponseBody
    public EChartData BarData() {
        List<Fruit> fruitList = fruitService.queryFruitGroupByNameAndLocation();
        List<String> categoryList = fruitList.stream().map(Fruit::getName).distinct().collect(Collectors.toList());
        List<String> legendList = fruitList.stream().map(Fruit::getLocation).distinct().collect(Collectors.toList());
        List<Series> series = new ArrayList<Series>();// 纵坐标
        // 分组数据统计
        for (String legend : legendList) {
            List<Long> seriesData = new ArrayList<Long>();
            for (Fruit fruit:fruitList){
                if (legend.equals(fruit.getLocation())){
                    seriesData.add(fruit.getWeight());
                }
            }
            series.add(new Series(legend,"bar",seriesData));
        }
        List<String> colorList = Arrays.asList(ChartUtil.getColorList(legendList.size()));
        return new EChartData(legendList, categoryList, series, colorList);
    }

}

5、FruitMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sophia.chart.fruit.FruitMapper">

    <select id="queryFruitGroupByNameAndLocation" resultType="Fruit">
        select t1.name,t2.location,sum(if(t3.weight is null,0,t3.weight)) weight
        from(select distinct name from t_fruit) t1
        inner join (select distinct location from t_fruit) t2 on 1=1
        left join t_fruit t3 on t1.name=t3.name and t2.location=t3.location
        group by t2.location,t1.name
        order by t2.location,t1.name
    </select>

</mapper>

6、前端BarChart.jsp

<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts柱状图</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/echarts-all.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
    $().ready(function () {
        var myChart = echarts.init(document.getElementById('main'));
        //图表显示提示信息
        myChart.showLoading();
        //定义图表options
        var options = {
            color: {
                data: []
            },
            title: {
                x: 'center', // 'center' | 'left' | {number},
                y: 'top', // 'center' | 'bottom' | {number}
                text: "通过Ajax获取数据呈现图标示例"
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                orient: 'horizontal', // 'vertical'
                x: 'center', // 'center' | 'left' | {number},
                y: 'bottom', // 'center' | 'bottom' | {number}
                data: []
            },
            toolbox: {
                show: true,
                feature: {
                    mark: false
                }
            },
            calculable: true,
            xAxis: [{
                type: 'category',
                data: []
            }],
            yAxis: [{
                type: 'value',
                splitArea: {
                    show: true
                }
            }],
            series: [{
                barWidth: '60%'
            }]
        };

        //通过Ajax获取数据
        $.ajax({
            type: "post",
            async: false, //同步执行
            url: "showEChartBar.action",
            dataType: "json", //返回数据形式为json
            success: function (result) {
                if (result) {
                    //将返回的category和series对象赋值给options对象内的category和series
                    //因为xAxis是一个数组 这里需要是xAxis[i]的形式
                    options.xAxis[0].data = result.category;
                    options.series = result.series;
                    options.legend.data = result.legend;
                    options.color = result.color;
                    myChart.hideLoading();
                    myChart.setOption(options);
                }
            },
            error: function (errorMsg) {
                alert("图表请求数据失败啦!");
            }
        });

    });
</script>
</body>
</html>

说明:

1、部分代码使用了Java8特性,编译时需要设置编译器版本(setting-java Complier)

2、考虑到柱状图分组数的不同,对颜色进行返回,必须是十六进制的字符串,返回Color对象会报错

效果图

统计不同水果在各城市的情况,横坐标为水果类别,纵坐标为重量,以城市进行分组。

以上数据随便造的,可以根据实际需求进行优化。

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!