Echarts餅圖展示動態數據

Echarts餅圖展示動態數據

注:本例是在SSM框架基礎上實現的,通過小服務程序也同樣可以實現;(不要糾結於此)

echarts.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"  prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>餅圖測試</title>
        <!-- 引入jQuery -->
        <script src="${ctx}/js/jquery-2.0.3.min.js" ></script>
        <!-- 引入echarts -->
        <script src="${ctx}/js/echarts.min.js" ></script>
		<script type="text/javascript">
			var json = [];
	        var datas =[];
			
			$(function(){
				//ajax調用
				ajaxGetData();
			});	                    

			function ajaxGetData(){
				$.ajax({
					url:"${ctx}/bug/user/getPie",
					type: "get",
					success:function(data){
						//以上兩種解析json的方法都可以
						//var jsonObject = JSON.parse(data);
						var jsonObject = eval("("+data+")");
						for(var i=0;i<jsonObject.length;i++){
							json.push({value:jsonObject[i].age,name:jsonObject[i].name});
							datas.push(jsonObject[i].name);
						}
						printPie();
					}
				});
			}
			
			function printPie(){
				var echartsPie = echarts.init(document.getElementById('echartsPie'));
				var option = {
					    title : {
					        text: '女神年齡分佈',
					        subtext: '獨家報道',
					        x:'center'
					    },
					    tooltip : {
					        trigger: 'item',
					        formatter: "{a} <br/>{b} : {c} 歲"
					    },
					    legend: {
					        orient : 'vertical',
					        x : 'left',
					        data:datas
					    },
					    toolbox: {
					        show : true,
					        feature : {
					            mark : {show: true},
					            dataView : {show: true, readOnly: false},
					            magicType : {
					                show: true, 
					                type: ['pie', 'funnel'],
					                option: {
					                    funnel: {
					                        x: '25%',
					                        width: '50%',
					                        funnelAlign: 'left',
					                        max: 1548
					                    }
					                }
					            },
					            restore : {show: true},
					            saveAsImage : {show: true}
					        }
					    },
					    calculable : true,
					    series : [
					        {
					            name:'女神',
					            type:'pie',
					            radius : '55%',//餅圖的半徑大小
					            center: ['50%', '60%'],//餅圖的位置
					            data:json
					        }
					    ]
					}; 
				echartsPie.setOption(option);
			}
			
		</script>
		
	</head>
	<body style="background-color: white;overflow-x:hidden;">
		<div style="min-width: 100%;">
			<div id="echartsPie" style="width: 600px;height:400px;"></div>
		</div>
	</body>
</html>

User.java文件

package com.java.bug.beans;
import org.apache.ibatis.type.Alias;

/**
 * 描述:用戶實體類
 */
@Alias("user")
public class User {

    private Long id;// 編號
    
    private String name;// 姓名
    
    private Long age;// 年齡
    

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

}

UserController.java文件

package com.java.bug.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.java.bug.beans.User;
import com.java.bug.service.IUserService;

import net.sf.json.JSONArray;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
	
	@Autowired
	IUserService userService;
	
	@RequestMapping(value="/getPie",method={RequestMethod.POST,RequestMethod.GET})
	public String getPie(HttpServletResponse response){
		Map<Object, Object> map = new HashMap<Object, Object>();
		List<User> userserList = userService.selectUserByCondition(map);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.write(JSONArray.fromObject(userserList).toString());// 餅圖
		out.flush();
		return null;
	}

}

UserService.java文件

package com.java.bug.service;

import java.util.List;
import java.util.Map;

import com.java.bug.beans.User;

/**
 * 描述:UserService
 */
public interface IUserService {

	/**
	 * 條件查詢 ||通過外鍵查詢
	 */
	public List<User> selectUserByCondition(Map<Object, Object> map);
}

UserServiceImpl.java文件

package com.java.bug.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.java.bug.beans.User;
import com.java.bug.dao.UserDao;
import com.java.bug.service.IUserService;

/**
 * 描述:UserServiceImpl
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

	@Autowired
	private  UserDao userDao;

	@Override
	public List<User> selectUserByCondition(Map<Object, Object> map) {
		return userDao.selectUserByCondition(map);
	}
}

UserDao.java文件

package com.java.bug.dao;


import java.util.List;
import java.util.Map;

import com.java.bug.beans.User;

/**
 * 描述:UserDao
 */
public interface UserDao extends BaseDao<User> {

	/**
	 * 條件查詢 
	 */
	public List<User> selectUserByCondition(Map<Object, Object> map);
}

User.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.java.bug.dao.UserDao">
	<!-- 條件查詢用到的查詢 -->
	<select id="selectUserByCondition"  parameterType="java.util.Map" resultType="user">
		SELECT * FROM User
		<where>
			1=1
		</where>
	</select>
</mapper>

User.sql文件(腳本)

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50623
Source Host           : localhost:3306
Source Database       : bug

Target Server Type    : MYSQL
Target Server Version : 50623
File Encoding         : 65001

Date: 2018-10-19 16:33:34
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `User`
-- ----------------------------
DROP TABLE IF EXISTS `User`;
CREATE TABLE `User` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of User
-- ----------------------------
INSERT INTO `User` VALUES ('1', '高圓圓', '20');
INSERT INTO `User` VALUES ('2', '趙麗穎', '22');
INSERT INTO `User` VALUES ('3', '江萊', '24');

效果圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章