从零开始的物联网毕业设计(中篇)

803 阅读6分钟

写在前面

本篇先完成后端部分,再完成前端部分,最终前后端结合测试,完成一个从网页对数据库查询并显示的简单功能。

总结了好长时间,创作不易,点点赞收收藏啦。

本文正在参加「金石计划」

后端部分

开发环境搭建

我用到的开发环境

用到哪些版本
java1.8.0
maven3.8.4
mysql5.7.19

开发工具:IDEA2021 ,Navicat

开发环境不用必须和我一样,开发工具自行下载破解

完成一个温度查询功能

1.在数据库中建表

在数据库中新建一个温度表sys_temp,用于存储温度信息,sql语句如下

CREATE TABLE `sys_temp` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `temp` float NOT NULL COMMENT '温度',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '删除标记(0:不可用 1:可用)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='温度表';

表建好后随便插入几条语句,方便一会验证查询功能

image.png

2.建立一个spring项目

在开发工具IDEA中,新建一个spring项目

image.png

依赖项中勾选spring web,点击完成项目建立成功

image.png

首先,配置maven仓库,点击左上角的文件——>设置——>构建、执行、部署——>构建工具——>Maven,打开如下界面,并配置你的maven路径,以及maven配置文件的路径,随后点击确定,配置完成

image.png

找到项目中的pom.xml文件在dependencies标签中添加如下依赖,然后让maven加载

   <!--MyBatisPlus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--数据库连接池druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>

image.png

在src/main/resources/application.properties配置文件中添加配置

spring.application.name=temptest
server.port=8088
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

其中端口号8080修改一下,避免与前端的端口号冲突,url中的mydb改成你自己数据库的名字,用户名和密码也设定为你自己的账号和密码

在com.atlhb.tempdemo目录下添加目录,参考下图

image.png

在entity目录下添加实体类Temp.java,代码如下

package com.atlhb.temptest.entity;

import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;

@TableName("sys_temp")
public class Temp {
    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField("temp")
    private Float temp;

    @TableField("create_time")
    private Date createTime;

    @TableField("update_time")
    private Date updateTime;

    @TableLogic
    @TableField("is_deleted")
    private Integer isDeleted;

    public Long getId() {
        return id;
    }

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

    public Float getTemp() {
        return temp;
    }

    public void setTemp(Float temp) {
        this.temp = temp;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }
}

在mapper目录下添加接口TempMapper.java,代码如下

package com.atlhb.temptest.mapper;

import com.atlhb.temptest.entity.Temp;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface TempMapper extends BaseMapper<Temp> {
}

在service目录下添加接口TempService.java,代码如下

package com.atlhb.temptest.service;

import com.atlhb.temptest.entity.Temp;
import com.baomidou.mybatisplus.extension.service.IService;

public interface TempService extends IService<Temp> {
}

在service/impl目录下添加实现类TempServiceImpl.java,代码如下

package com.atlhb.temptest.service.impl;

import com.atlhb.temptest.entity.Temp;
import com.atlhb.temptest.mapper.TempMapper;
import com.atlhb.temptest.service.TempService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class TempServiceImpl extends ServiceImpl<TempMapper, Temp> implements TempService {
}

在controller目录下添加控制类TempController.java,代码如下

package com.atlhb.temptest.controller;

import com.atlhb.temptest.entity.Temp;
import com.atlhb.temptest.service.TempService;
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 TempController {

    @Autowired
    private TempService service;

    @GetMapping("/temp")
    public List<Temp> findAll(){
        List<Temp> list = service.list();
        return list;
    }
}

在com.atlhb.temptest.TemptestApplication启动类中添加一行注解@MapperScan("com.atlhb.tempdemo.mapper")来扫描mapper层

package com.atlhb.temptest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.atlhb.temptest.mapper")
public class TemptestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TemptestApplication.class, args);
    }
}

所有文件添加完成后的目录如下图

image.png

3.验证后端是否成功

在启动类com.atlhb.tempdemo.TempdemoApplication中启动项目

image.png

在浏览器中访问localhost:8088/temp

出现数据,代表后台访问数据库成功

image.png

前端部分

开发环境搭建

1.下载VSCode

下载地址:Visual Studio Code - Code Editing. Redefined

image.png

自行下载安装即可,打开后界面长这样

image.png

2.下载node.js

下载地址:Node.js (nodejs.org)

image.png

下载完成安装包长这样

image.png

安装过程中选好自己的安装路径,基本就是一路next,除了下面这个界面记得要勾选

image.png

出现下面这个界面代表安装完成

image.png

接下来验证是否安装成功,进入命令行界面,输入node -v,若出现版本号,代表安装成功(看清node -v中间有一个空格)

image.png

3.安装脚手架

在命令行中输入npm install -g @vue/cli

下载完成如下图

image.png

实现一个简单的网页

1.准备工作

首先准备一个你放代码的路径,在其中新建一个文件夹以你的前台项目命名,我以demo为例

在命令行中打开你项目的路径,输入vue create 自定义项目名

image.png

回车显示下图,用键盘上下键选择vue2(我以vue2为例),按回车等待片刻

image.png

出现下图代表搭建完成,我们回到刚才新建的空白项目文件夹,可以看到出现了许多文件

image.png

image.png

我们将外层的demo文件夹在vscode中打开,右键内层的demo文件夹,选择在集成终端中打开

image.png

在集成终端中输入npm run serve,等待运行完成后出现下图所示网址,我们访问第一个网址

image.png

看到vue主页,代表准备工作已经完成

image.png

2.安装官方库

在集成终端中打开,输入npm install axios,npm install vue-router@3,npm install vuex@3,出现下图代表安装成功

image.png

3.搭建网页

将demo\src\components下的文件HelloWorld.vue删除,在这个文件夹中新建文件tempV.vue(后面跟一个单词进行驼峰命名否则可能会报错),将下面的代码复制进tempV.vue文件

<template>
  <div>
    <button @click="getTemp">查询温度</button>
    <hr>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
    name:'tempV',
    methods:{
        getTemp(){
           this.$router.push('list')
        }
    }
}
</script>

<style>

</style>

在src目录下新建文件夹pages,在文件夹中新建文件listV.vue将下面代码复制进去

<template>
  <div class="tabl">
    <table width="90%" class="table">
        <caption>
            <h2>
              温度检测表
            </h2>
        </caption>
        <thead>
            <tr>
                <th>
                    编号
                </th>
                <th>
                    温度
                </th>
                <th>
                    创建时间
                </th>
            </tr>
        </thead>
        <tr v-for="(item,index) in user" :key="index">
            <td>
              {{ item.id }}
            </td>
            <td>
              {{ item.temp }}
            </td>
            <td>
              {{ item.createTime }}
            </td>
        </tr>
    </table>
  </div>
</template>
  
<script>
    import {mapState} from 'vuex'
    export default {
        name: "listV",
        mounted(){
          this.$store.dispatch('getUser')
        },
        computed:{
          ...mapState(['user'])
        }
    };
</script>
  
<style type="text/css">
table
{
    border-collapse: collapse;
    margin: 0 auto;
    text-align: center;
}
table td, table th
{
    border: 1px solid #cad9ea;
    color: #666;
    height: 30px;
}
table thead th
{
    background-color: #CCE8EB;
    width: 100px;
}
table tr:nth-child(odd)
{
    background: #fff;
}
table tr:nth-child(even)
{
    background: #F5FAFA;
}
</style>

在src目录下新建文件夹router,在文件夹中新建文件router.js将下面代码复制进去

import VueRouter from 'vue-router'
import list from '@/pages/listV.vue'
const router = new VueRouter({
    routes:[
        {
            name:'list',
            component:list,
            path:'/list'
        }
    ]
})

export default router

在src目录下新建文件夹store,在文件夹中新建文件index.js将下面代码复制进去

import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'
Vue.use(Vuex)
const state={
    user:[]
}
const actions={
    async getUser({commit}){
        let result = await axios.get("http://localhost:8080/temp")
        console.log(result)
        if(result.status==200){
            commit('GETUSER',result.data)
        }
    }
}
const mutations={
    GETUSER(state,user){
        state.user = user || undefined
    }
}
const getters={}
export default new Vuex.Store({
    state,
    actions,
    mutations,
    getters
})

找到src\main.js,将下面的代码全部替换

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import router from './router/router'
import store from '@/store'
Vue.config.productionTip = false

Vue.use(VueRouter)
new Vue({
  render: h => h(App),
  router,
  store
}).$mount('#app')

找到src\App.vue,将下面的代码全部替换

<template>
  <div id="app">
    <temp></temp>
  </div>
</template>

<script>
import temp from "@/components/tempV.vue"

export default {
  name: 'App',
  components: {
    temp
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

找到vue.config.js,将下面的代码全部替换

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: 'http://localhost:8088'
  }
})

注意:这里的http://localhost:8088的端口号,要与后端设定的端口号保持一致

将上面所有的文件配置完成,目录如下

image.png

4.前端测试

选择再终端中打开,输入指令npm run serve,等待运行,运行成功出现下图,访问第一个网址

image.png

点击网页中的查询按钮,下方出现一个温度检测表,说明前端部分已经搭建成功

image.png

前后端结合进行测试

1.在后端的启动类文件中启动后端

image.png

2.在集成终端中启动前端

在集成终端中输入npm run serve,等待运行,下图代表运行成功

image.png

3.在网页中测试能否通过后端拿到数据库中的数据

访问 http://localhost:8080/ ,显示查询温度按钮

image.png

点击按钮,出现温度检测表,表中数据为数据库中所存数据

image.png

那么网页部分就已经大功告成了!

写在后面

下一篇也就是最后一篇讲解如何把硬件采集到的数据自动传入数据库,并通过本篇章写好的网页对其进行查询与显示。

老样子,有任何疑问,侵权或者错误的地方,请联系我QQ572130280