1、创建springboot项目,添加 web、jpa、lombok、mysql、jdbc 启动器,加载pom.xml。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xkxx</groupId>
<artifactId>chart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>chart</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、在resources下,将application.properties文件后缀改成.yml
server:
port: 8888
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/china?useSSL=false&serverTimezone=GMT%2B8
username: root
password: sasa
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database: mysql
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
main:
allow-bean-definition-overriding: true
3、编写统计对象Phone(由于数据库表过于简单,在此忽略)idea使用了lombok插件
package com.xkxx.chart.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name = "phone")
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",unique = true,nullable = false,length = 50)
@JsonIgnore //不返回id
private Integer id;
@Column(name = "name",nullable = false,length = 50)
private String name;
@Column(name = "num",nullable = false,length = 50)
private String num;
}
4、编写dao(使用SpringDataJpa)
package com.xkxx.chart.dao;
import com.xkxx.chart.entity.Phone;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PhoneDao extends JpaRepository<Phone,Integer> {
}
5、5、编写service,调用dao接口方法,返回信息
package com.xkxx.chart.service;
import com.xkxx.chart.dao.PhoneDao;
import com.xkxx.chart.entity.Phone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class PhoneService {
@Autowired
private PhoneDao phoneDao;
public List<Phone> findAll(){
return phoneDao.findAll();
}
}
6、编写web,调用service方法,实现数据与前端交互
package com.xkxx.chart.web;
import com.xkxx.chart.entity.Phone;
import com.xkxx.chart.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class IndexController {
@Autowired
private PhoneService phoneService;
@GetMapping("/phone")
public List<Phone> findAll(){
return phoneService.findAll();
}
}
7、编写CorsConfig类进行前后端分离跨域请求
package com.xkxx.chart.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 初始化 CorsConfiguration 对象并设置允许的域名、请求头部信息和请求方式
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2 允许任何头
corsConfiguration.addAllowedMethod("*"); // 3 允许任何方法(post、get 等)
return corsConfiguration;
}
/**
* 创建 CorsFilter 对象
* @return CorsFilter
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //拦截所有请求
return new CorsFilter(source);
}
}
8、后端最终样式
1、创建vue项目(如何创建vue项目?)
2、安装 axios 插件,在当前项目下的终端输入命令: npm install --save axios vue-axios
导入v-charts,输入命令:npm install echarts v-charts --save-dev(什么是v-charts?)
3、在 src 文件夹下的程序入口 main.js 中导入
import axios from 'axios'
import VueAxios from 'vue-axios'
// element-ui 引入文件
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//注册 VueAxios, axios
Vue.use(VueAxios, axios)
Vue.use(ElementUI)
4、在src的main.js下导入插件
import axios from 'axios'
import VueAxios from 'vue-axios'
import VCharts from 'v-charts'
Vue.use(VCharts)
//注册 VueAxios, axios
Vue.use(VueAxios, axios)
5、创建vue文件,编写柱状图
<template>
<ve-histogram :data="chartData" :title="chartTitle" :settings="chartSettings" :extend="extend"></ve-histogram>
</template>
<script>
const axios = require("axios");
import "echarts/lib/component/title";
export default {
data () {
this.chartSettings = {
yAxisType: ['KMB'],
yAxisName: ['销量/万'],
},
this.extend = {
barWidth: 25,//设置宽度为15px
// x轴的文字倾斜
'xAxis.0.axisLabel.rotate': 45,
'xAxis.0.axisLabel.fontSize': 20,//x轴文本字体大小
'xAxis.0.axisLabel.fontWeight': 'bold',//x轴文本字体粗细
series: {
label: { show: true, position: "top" },
color: function (value) { return "#" + ("00000" + ((Math.random() * 16777215 + 0.5) >> 0).toString(16)).slice(-6); }
}
},
this.chartTitle = {
// 文字啥的,用\n可以换行
text: '2019各大手机品牌销量',
x: '25px',
textStyle: {
fontSize: 20,
fontWeight: 'normal',
}
}
return {
chartData: {
columns: ['name', 'num'],
rows: []
}
}
},
created: function () {
var app = this;
console.log("init");
this.init()
},
methods: {
init: function () {
var app = this;
axios
.get("http://localhost:8888/phone")
.then(function (response) {
app.chartData.rows = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
}
</script>
展示效果
6、创建vue文件,编写饼状图
<template>
<ve-pie :data="chartData" :title="chartTitle" :events="chartEvents" :settings="chartSettings"></ve-pie>
</template>
<script>
const axios = require("axios");
import "echarts/lib/component/title";
export default {
data () {
var self = this
this.chartEvents = {
click: function (e) {
self.name = e.name
alert(e.name + ":" + e.percent);
console.log(e)
}
},
this.chartSettings = {
radius: 150,
offsetY: 250,
label: {
normal: {
fontSize: 16,
formatter: '{b}' + '\n\r' + '{c}' + '\n\r' + '({d}%)'
}
}
},
this.chartTitle = {
// 文字啥的,用\n可以换行
text: '2019各大手机品牌销量',
x: '25px',
textStyle: {
fontSize: 20,
fontWeight: 'normal',
}
}
return {
chartData: {
columns: ['name', 'num'],
rows: []
}
}
},
created: function () {
var app = this;
console.log("init");
this.init()
},
methods: {
init: function () {
var app = this;
axios
.get("http://localhost:8888/phone")
.then(function (response) {
app.chartData.rows = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
}
</script>
展示效果