> 文档中心 > 快速上手springboot实现前后端交互(以echarts为例)

快速上手springboot实现前后端交互(以echarts为例)


快速上手springboot实现前后端交互(以echarts为例)

1、安装JDK及下载开发工具

​ JDK是java的开发工具包,是编译及运行Java程序必备的。JDK下载及安装步骤

​ 开发工具的话目前主流的有Eclipse和IntelliJ IDEA,这里推荐idea,因为eclipse提示代码信息和界面设计都不如idea。

​ idea下载安装及配置JDK环境步骤:

2、什么是springboot

​ 在了解springboot之前,我们可以先了解以下spring,spring它是一个轻量级的开发框架,是为了简化应用开发而创建的。但是呢,随着其他技术(Node JS,Ruby,Groovy,Scala等)的发展,spring的开发模式越来越显得笨重(因为它要配置大量的xml文件以及第三方整合配置)。所以这时候需要一个更加简化开发的框架,所以springboot诞生了,springboot框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置,很多配置只需要一两个注解就可以解决。所以spring官网也建议直接使用springboot进行开发。

3、创建springboot项目

1、点击IDEA左上角file->new->project
快速上手springboot实现前后端交互(以echarts为例)

2、选择Spring Initializr ,点击Next

快速上手springboot实现前后端交互(以echarts为例)

3、这一页也不需要什么操作,其中选项对应的含义如下:

  • Group:项目创建后对应JAVA的包的结构,就是main目录里java的目录结构

  • Artifact:对应项目的名称,就是项目根目录的名称,注意不能有大写字符

  • Type:项目的构建方式,这里选择Maven(默认)

  • Language:开发语言,选择java(默认)

  • Packaging:打包方式,选择Jar(默认)

  • Java version:jdk的版本号,这里推荐Java8及以上即可

  • Version:是项目的版本号

  • Package:启动类所在的包

    4、完成后点击Next

快速上手springboot实现前后端交互(以echarts为例)

5、在这一页中是选择我们要引入的包,这里可以直接勾选引入,也可以创建项目之后再手动引入。右上角是springboot的版本,默认即可,如果之后和其他一些包版本冲突。(这里就先什么都不选,待会手动导入),点击Next

快速上手springboot实现前后端交互(以echarts为例)

6、这一页是项目路径,选择好项目路径后点击Finish,创建项目。

快速上手springboot实现前后端交互(以echarts为例)

4、导入一个Web项目的基本包

在讲这一步之前,我们先简单了解以下什么是maven,简单来说,maven就是用来存放和管理项目所需jar包的一个仓库,我们可以通过maven来导入我们所需要的依赖(工具),就不需要手动去下载jar包,maven会自动帮你引入,你只需要在pom.xml文件中写入包名及版本号即可。

1、找到pom.xml文件并打开,pom文件就是springboot项目导包的地方

快速上手springboot实现前后端交互(以echarts为例)

2、应为我们之前什么都没勾选,所以此时pom文件中只有springboot启动器和test包。

    <dependencies>  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter</artifactId> </dependency> <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-test</artifactId>     <scope>test</scope> </dependency>    </dependencies>

3、导入所需依赖

    <dependencies>  <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> </dependency>   <dependency>     <groupId>com.baomidou</groupId>     <artifactId>mybatis-plus-boot-starter</artifactId>     <version>3.2.0</version> </dependency>  <dependency>     <groupId>com.baomidou</groupId>     <artifactId>mybatis-plus-generator</artifactId>     <version>3.2.0</version> </dependency>  <dependency>     <groupId>org.apache.velocity</groupId>     <artifactId>velocity-engine-core</artifactId>     <version>2.0</version> </dependency>  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>   <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId> </dependency>    </dependencies>

4、此时右上角会出现这个按钮,点击按钮开始下载上面导入的包。

快速上手springboot实现前后端交互(以echarts为例)

5、配置数据库连接及服务端口等基础配置

因为要从数据库取数据,所以必不可少的一步就是要配置数据库连接信息,springboot关于数据库的配置application.properties或者application.yml文件中的,springboot创建后会自带一个application.properties文件,所以打开它并配置信息。这里再application.properties文件中,不仅可以配置数据库连接信息,还可以有很多springboot的配置,

快速上手springboot实现前后端交互(以echarts为例)

# 服务端口,默认8080server.port=8012# mysql数据库连接# 数据库驱动spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# 数据库的地址,及其使用的具体库名及一些其他的参数。spring.datasource.url=jdbc:mysql://localhost:3306/springboot_project?serverTimezone=UTC&useSSl=true&useUnicode=true&characterEncoding=UTF-8# 指定的数据库用户名spring.datasource.username=root# 指定的数据库密码spring.datasource.password=123456#关闭thymeleaf缓存,实现热部署。也就是修改了html后不用重启,刷新页面就能看到效果,# 注意修改完html后一定要ctrl+f9重新build一下。再回到浏览器刷新,就能看到效果了spring.thymeleaf.cache=false

6、利用mybatis-plus代码生成器生成controller层等

我们使用的操作数据库框架是mybatis-plus,它是在对原来的mybatis的功能不变的情况下新增了很多功能,可以方便开发。关于他们细节上的不同可参考https://blog.csdn.net/qq_34508530/article/details/88943858? 简单来说就是mp有了很多内置的查询数据库的方法,除了一些复杂的SQL语句外,基本上可以不用编写SQL语句,直接调用方法即可,同时,它还提供了一个很牛的功能-----代码生成器,只需要基本固定的代码就可以快速生成实体类(pojo)、业务控制(Controller)层、服务(service)层等。下面附上代码

public void codeGenerator() {     // 1、创建代码生成器     AutoGenerator mpg = new AutoGenerator();     // 2、全局配置     GlobalConfig gc = new GlobalConfig();     String projectPath = System.getProperty("user.dir");     gc.setOutputDir(projectPath + "/src/main/java");//生成代码位置     gc.setOpen(false); //生成后是否打开资源管理器     gc.setFileOverride(false); //重新生成时文件是否覆盖     gc.setAuthor("mhz");//设置作者名 /*  * mp生成service层代码,默认接口名称第一个字母有 I  *   * */     gc.setServiceName("%sService"); //去掉Service接口的首字母I     gc.setIdType(IdType.ID_WORKER_STR); //主键策略     gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型     gc.setSwagger2(false);//开启Swagger2模式     mpg.setGlobalConfig(gc);     // 3、数据源配置     DataSourceConfig dsc = new DataSourceConfig();     dsc.setUrl("jdbc:mysql://localhost:3306/springboot_project?serverTimezone=UTC&useSSl=true&useUnicode=true&characterEncoding=UTF-8");     dsc.setDriverName("com.mysql.cj.jdbc.Driver");     dsc.setUsername("root");     dsc.setPassword("123456");     dsc.setDbType(DbType.MYSQL);     mpg.setDataSource(dsc);     // 4、包配置     PackageConfig pc = new PackageConfig();     pc.setModuleName("echartsdemo"); //模块名     pc.setParent("com.mhz");//设置包名     pc.setController("controller");//设置controller层名字     pc.setEntity("pojo");//设置实体类层名字     pc.setService("service");//设置service层名字     pc.setMapper("mapper");//设置mapper层名字     mpg.setPackageInfo(pc);     // 5、策略配置     StrategyConfig strategy = new StrategyConfig();     strategy.setInclude("movie");//设置要生成的数据库表的名字     strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略     strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀     strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略     strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作     strategy.setRestControllerStyle(true); //restful api风格控制器     strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符     mpg.setStrategy(strategy);     // 6、执行     mpg.execute(); }

代码执行后,就会生成如下的结构,生成代码后记得在mapper接口文件中添加@Mapper注解。此时基本结构就完成了,接下来就是前端页面的构造。

快速上手springboot实现前后端交互(以echarts为例)

快速上手springboot实现前后端交互(以echarts为例)

  • controller层:就是前端调用的接口,用来向前端传输数据以及控制路由跳转。
  • mapper层:用来写操作数据库的方法及sql语句。
  • 实体类(pojo):用来映射数据表里的字段。
  • service层:用来写一些业务逻辑,封装Service层的业务逻辑有利于业务逻辑的独立性和重复利用性。
  • 启动类:用来启动项目。

7、前端页面构造

​ 前端页面也可以在idea中完成,不需要下载其他前端开发工具,idea本身前端代码提示功能及代码高亮部分就做的很好,所以可以直接在idea中构建。前端html页面有很多框架,例如bootstrapAmaze UI 等,大家开发中可以利用这些框架,方便页面制作。这里为了看起来简单,就简单演示最基础的html页面的交互。前端页面建议放在resources文件夹下,可以为页面单独建个包,方便管理,这里注意像前端页面及静态资源文件不要乱放位置,因为springboot中有句话叫“约定大于配置”,静态资源需要放在它指定的文件夹下才能访问到(classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/)。

​ 这里需要了解的知识点就是thymeleaf,thymeleaf是springboot推荐的模板引擎,可以用来渲染前端页面,我们这个应用中主要就是用它的内联表达式来接收后端传值以及页面的跳转。这里附上它的一个中文文档 thymeleaf中文文档,注意一点,如果我们引入了 thymeleaf的话,也要遵守它的配置,html文件都要放在templates文件夹下。

使用具体操作如下图:

1、创建一个放前端页面的包

快速上手springboot实现前后端交互(以echarts为例)快速上手springboot实现前后端交互(以echarts为例)

2、创建html页面

快速上手springboot实现前后端交互(以echarts为例)快速上手springboot实现前后端交互(以echarts为例)

3、接下来就是创建echarts实例及配置,主要就是五部:

  • 1、直接引入echarts的cdn或者下载echarts.js后导入。
  • 2、为 ECharts 准备一个具备大小(宽高)
  • 3、基于准备好的dom,初始化echarts实例
  • 4、指定图表的配置项和数据
  • 5、使用刚指定的配置项和数据显示图表。

8、后端数据的传输

后端像前端传数据就是通过controller层的接口,步骤如下:

1、进入controller层

快速上手springboot实现前后端交互(以echarts为例)

2、创建一个向前端传数据的接口等前端调用,这里记住前端需要什么结构的数据就传什么数据。

@RestController@RequestMapping("")public class StatisticsDailyController {    @Autowired    StatisticsDailyService dailyService;    @GetMapping("line")    public Map<String, Object> showLineChart(Model model) { QueryWrapper<StatisticsDaily> dayQueryWrapper = new QueryWrapper<>();//构造查询条件 dayQueryWrapper.select("login_num", "date_calculated");//向条件中添加条件,这里的意思是只查询表中“login_num”,“date_calculated”两个字段的数据,相当于SQL语句select 'login_num','date_calculated' from statistics_daily List<StatisticsDaily> dayList = dailyService.list(dayQueryWrapper);//执行语句,得到数据  //对数据进行处理,得到前端需要的数据结构 List<String> calculatedList = new ArrayList<>(); List<Integer> numDateList = new ArrayList<>(); for (StatisticsDaily daily : dayList) {     calculatedList.add(daily.getDateCalculated());     numDateList.add(daily.getLoginNum()); } Map<String, Object> map = new HashMap<>(); map.put("calculatedList", calculatedList); map.put("numDateList", numDateList); return map;    }}

9、前端调用后端接口接收数据

前端调用后端接口,主流的就是利用ajax进行异步调用,还有axios等,这里就用ajax进行调用,有兴趣的同学可以了解以下ajax和axios的区别:

这里有个知识点就是json,json就是一种数据格式,简单来说就是键值对的数据。它的主要语法如下:

  • 数据在名称/值对中

  • 数据由逗号分隔

  • 花括号保存对象

  • 方括号保存数组

    形式如下:

    {  "name": "计算机必修课",  "children": [    {      "name": "后端开发",      "children": [ {   "name": "Java" }, {   "name": "Python" }      ]    },    {      "name": "前端开发",      "children": [ {   "name": "JavaScript" }, {   "name": "HTML/CSS" }, {   "name": "bootstrap" }      ]    },    {      "name": "云计算",      "children": [ {   "name": "Docker" }, {   "name": "Linux" }      ]    },    {      "name": "系统/运维",      "children": [ {   "name": "Linux" }, {   "name": "Windows" }      ]    },    {      "name": "数据库",      "children": [ {   "name": "MySQL" }, {   "name": "MongoDB" }      ]    },    {      "name": "大数据",      "children": [ {   "name": "Hadoop" }, {   "name": "Spark" }      ]    },    {      "name": "人工智能",      "children": [ {   "name": "Python" }      ]    },    {      "name": "编程语言",      "children": [ {   "name": "Java" }      ]    }  ]}

为了方便使用ajax,这里建议先导入Jquery的包或者cdn,因为Jquery对ajax进行了封装,用起来方便很多。ajax的主要用法如下:

    $.ajax({ type: "GET",   //请求方式 url: "getUser",    //请求路径 // data:{"id":val},     // data参数是可选的,有多种写法,也可以直接在url参数拼接参数上去,例如这样:url:"getUser?id="+val, data: "id=" + val, async: true,   // 异步,默认开启,也就是$.ajax后面的代码是不是跟$.ajx里面的代码一起执行 cache: true,  // 表示浏览器是否缓存被请求页面,默认是 true dataType: "json",   // 返回浏览器的数据类型,指定是json格式,前端这里才可以解析json数据 success: function (data) {    //方法执行成功后的回调函数     $("#name").text(data.name);     $("#age").text(data.age); }, error: function () {      //方法执行失败后的回调函数     console.log("发生错误")     alert("发生错误"); },    });

所以最后的前端代码如下:

<head>    <meta charset="UTF-8">    <title>数据可视化</title></head><body><script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script><div id="main" style="width: 600px;height:500px;"></div><div>    <button id="show">图表展示</button></div><script type="text/javascript">    // 基于准备好的dom,初始化echarts实例    var myChart = echarts.init(document.getElementById('main'));    // 当button按钮被点击时执行    $("#show").click(function show() { // ajax异步调用后端接口 $.ajax({     type : "get",   //请求方式     url : "/line",  //后端controller层路径     contentType: 'application/json',     success:function(data){  option = {      title: {   text: '网站每日登录人数'      },      xAxis: {   type: 'category',   data: data.calculatedList    //x轴数据      },      yAxis: {   type: 'value'      },      toolbox: {   show: true,   feature: {mark: {show: true},dataView: {show: true, readOnly: false},restore: {show: true},saveAsImage: {show: true}   }      },      tooltip: {   trigger: 'axis',   axisPointer: {     // 坐标轴指示器,坐标轴触发有效type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'   }      },      series: [{   data: data.numDateList,   //y轴数据   type: 'line',   showBackground: true,   color: '#18cbdb',      }]  };  // 使用刚指定的配置项和数据显示图表。  myChart.setOption(option);     },     error:function(data){  console.log("error")  console.log(data)     } })    })    </script></body></html>

10、启动springboot启动类

运行springboot启动类,打开网页(http://localhost:端口号/),端口号默认8080,如果你前面在application.properties文件中配置过端口,就填你写的那个端口号。

快速上手springboot实现前后端交互(以echarts为例)

11、查看效果

打开网页:

快速上手springboot实现前后端交互(以echarts为例)

点击图表展示按钮:

快速上手springboot实现前后端交互(以echarts为例)

12、附:ajax调用本地json数据展示代码

本地json数据

[  {    "value": 1048,    "name": "搜索引擎"  },  {    "value": 735,    "name": "直接访问"  },  {    "value": 580,    "name": "邮件营销"  },  {    "value": 484,    "name": "联盟广告"  }]

html页面

<html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title></head><body>        <div id="main" style="width: 600px;height:500px;"></div>        <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script>        <script src="https://lib.baomitu.com/echarts/5.0.2/echarts.common.js"></script>    <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); var option; $.ajax({     type: "get",  //请求方式     url: "pie.json",  //本地json文件,记得写对路径,要写相对路径,绝对路径可能会找不到     contentType: 'application/json',     success: function (data) {  option = {      tooltip: {   trigger: 'item'      },      legend: {   top: '5%',   left: 'center'      },      series: [   {name: '访问来源',type: 'pie',radius: ['40%', '70%'],avoidLabelOverlap: false,itemStyle: {    borderRadius: 10,    borderColor: '#fff',    borderWidth: 2},label: {    show: false,    position: 'center'},emphasis: {    label: { show: true, fontSize: '40', fontWeight: 'bold'    }},labelLine: {    show: false},data: data  //使用请求来的数据展示   }      ]  };  myChart.setOption(option);     },     error: function (data) {  console.log("error")  console.log(data)     } })    </script></body></html>

效果展示

快速上手springboot实现前后端交互(以echarts为例)

13、附:axios演示

本地json

{    "name": "计算机必修课",    "children": [ {     "name": "后端开发",     "children": [  {      "name": "Java"  },  {      "name": "Python"  }     ] }, {     "name": "前端开发",     "children": [  {      "name": "JavaScript"  },  {      "name": "HTML/CSS"  },  {      "name": "bootstrap"  }     ] }, {     "name": "云计算",     "children": [  {      "name": "Docker"  },  {      "name": "Linux"  }     ] }, {     "name": "系统/运维",     "children": [  {      "name": "Linux"  },  {      "name": "Windows"  }     ] }, {     "name": "数据库",     "children": [  {      "name": "MySQL"  },  {      "name": "MongoDB"  }     ] }, {     "name": "大数据",     "children": [  {      "name": "Hadoop"  },  {      "name": "Spark"  }     ] }, {     "name": "人工智能",     "children": [  {      "name": "Python"  }     ] }, {     "name": "编程语言",     "children": [  {      "name": "Java"  },  {      "name": "C++"  },  {      "name": "C#"  }     ] }    ]}

html页面

<html><head>    <meta charset="UTF-8">    <title></title>    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /></head><body>        <div id="main" style="width: 600px;height:500px;"></div>    <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>    <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); var option; axios.get('tree.json').then(response => {     var dataTree = response.data     option = {  title: {      text: '计算机技术栈树形图'  },  tooltip: {      trigger: 'item',      triggerOn: 'mousemove'  },  series: [      {   type: 'tree',   data: [dataTree],   top: '1%',   left: '7%',   bottom: '1%',   right: '20%',   symbolSize: 7,   label: {position: 'left',verticalAlign: 'middle',align: 'right',fontSize: 9   },   leaves: {label: {    position: 'right',    verticalAlign: 'middle',    align: 'left'}   },   emphasis: {focus: 'descendant'   },   expandAndCollapse: true,   animationDuration: 550,   animationDurationUpdate: 750      }  ]     };     console.log(dataTree)     myChart.setOption(option); })    </script></body></html>