springboot(十六)echarts报表的使用

x33g5p2x  于2021-12-17 转载在 Echarts  
字(6.1k)|赞(0)|评价(0)|浏览(1211)

前言:

      在开发过程中少不了对报表的整合,虽然我们后端只提供数据,但是也避免不了自己来实现前端的可能。所以我们也得简单得了解下echarts的使用!

      接下来我们完成查询数据库并让数据生成可视化的报表!

实现:

   数据库:商品表

CREATE TABLE `product` (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '',
  `num` int(11) NOT NULL DEFAULT '0',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`pid`,`product_name`,`num`,`create_time`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

   新建项目sprinboot-echarts,打开pom.xml

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
			<!--springdata jpa-->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-data-jpa</artifactId>
			</dependency>
			<!--web-->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-web</artifactId>
			</dependency>
			<!--mysql-->
			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>5.1.44</version>
			</dependency>
			<!--druid连接池-->
			<dependency>
				<groupId>com.alibaba</groupId>
				<artifactId>druid-spring-boot-starter</artifactId>
				<version>1.1.10</version>
			</dependency>
			<!--test-->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-test</artifactId>
				<scope>test</scope>
			</dependency>
			<!--lombok-->
			<dependency>
				<groupId>org.projectlombok</groupId>
				<artifactId>lombok</artifactId>
				<version>1.16.22</version>
			</dependency>

	</dependencies>

  配置application.properties资源文件

#配置静态资源文件路径
spring.mvc.static-path-pattern=/static/**

#数据库配置
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot2?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

#jpa配置
spring.jpa.database=mysql
#是否显示sql
spring.jpa.show-sql=true
# create       每次运行该程序,没有表会新建表,表内有数据会清空
# create-drop  每次程序结束的时候会清空表
# update       每次运行程序,没有表会新建表,表内有数据不会清空,只会更新
# validate     运行程序会校验数据与数据库的字段类型是否相同,不同会报错
spring.jpa.hibernate.ddl-auto=update

#指定日期格式 yyyy-MM-dd HH:mm:ss
spring.jackson.date-format: yyyy-MM-dd HH:mm:ss
#mvc序列化时候时区选择
spring.jackson.time-zone: GMT+8

  实体对象Product.java

@Data
@Entity
public class Product implements Cloneable{
    //id 商品ID
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int pid;
    //商品名称
    private String productName;
    //商品数量
    private int num;
    //创建时间
    private Date create_time;

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

}

      注:大家可能会疑惑我为什么要实现Cloneable接口,这里是为了后面演示添加数据时复制对象用的。调用clone复制对象

 编写ProductReposity.java

public interface ProductReposity extends JpaRepository<Product,Integer>{
}

 编写ProductService.java

public interface ProductService {
    List<Product> findAll();

    List<Product> adds(List<Product> list);

}

 编写ProductServiceImpl.java

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductReposity reposity;

    @Override
    public List<Product> findAll() {
        return reposity.findAll();
    }

    @Override
    public List<Product> adds(List<Product> list) {
       return reposity.saveAll(list);
    }
}

 编写测试类添加数据.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootEchartsApplicationTests {

    @Resource
    private ProductService productService;

    @Test
    public void add() {
        Product p = new Product();
        p.setPid(1);
        p.setProductName("鞋子");
        p.setNum(20);
        Product p1 = (Product) p.clone();
        p1.setPid(2);
        p1.setProductName("袜子");
        p1.setNum(30);
        Product p2 = (Product) p.clone();
        p2.setPid(3);
        p2.setProductName("衣服");
        p2.setNum(50);
        Product p3 = (Product) p.clone();
        p3.setPid(4);
        p3.setProductName("裤子");
        p3.setNum(60);

        List<Product> products = Arrays.asList(p, p1, p2, p3);
        try {
            productService.adds(products);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    @Test
    public void findAll() {
        List<Product> all = productService.findAll();
        System.out.println(all);
    }
}

     注:clone()方法实现完全复制,这也是我们的原型模式中的浅拷贝方式

            原型模式:https://blog.csdn.net/xu12387/article/details/88941419

编写ProductController.java

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @GetMapping("/list")
    @ResponseBody
    public Map<String,List> findAll(){
        List<Product> list = productService.findAll();
        List<String> productNameList = list.stream().map(Product::getProductName).collect(Collectors.toList());
        List<Integer> numList = list.stream().map(Product::getNum).collect(Collectors.toList());
        Map<String,List> map=new HashMap<>();
        map.put("productName",productNameList);
        map.put("num",numList);
        return map;
    }

}

  添加js文件resouce/static

 编写index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>ECharts</title>
    <script src="/static/echarts.min.js"></script>
    <script src="/static/jquery.min.js"></script>
</head>

<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>

<script type="text/javascript">
    // 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));
    // 显示标题,图例和空的坐标轴
    myChart.setOption({
        title: {
            text: '商品数量'
        },
        tooltip: {},
        legend: {
            data: ['库存量']
        },
        xAxis: {
            data: []
        },
        yAxis: {},
        series: [{
            name: '库存量',
            type: 'bar',
            data: []
        }]
    });
    //加载动画
    myChart.showLoading();
    // 异步加载数据
    $.get('list').done(function(data) {
        // 填入数据
        myChart.setOption({
            xAxis: {
                data: data.productName
            },
            series: [{
                //根据名字对应到相应的系列
                name: '库存量',
                type: 'bar',
                data: data.num
            }]
        });
        myChart.hideLoading();
    });
</script>
</body>

</html>

       注:更多echarts案例访问官网:https://echarts.baidu.com/examples/

              如果没使用模板,外部调用接口,注意跨域问题哟!

              跨域解决:https://blog.csdn.net/xu12387/article/details/88869749

测试:

  访问localhost:8080/index

源码地址:https://gitee.com/xu0123/springboot2

相关文章