SpringBoot+Vue前后端分离(CURD)Demo

我发现我好久没有更新了,写一篇证明我还活着。
既然是前后端分离的话,肯定是要有前端和后端的。
这里前端我使用的Vue+ElementUI,后端采用的是SpringBoot+Mybatis+Swagger2。
下面的话,我就做一个简单的Demo吧。
写的不好,请大家各位大佬们指点

1、后端

后端的话,我是使用之前基础上面改的。EasyCode(代码神器)

1.1 pom.xml

   <!--Swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>

1.2 添加Swagger配置类

image.png
/**
 * Swagger2
 * 该项目访问地址:http://127.0.0.1:8089/doc.html
 * @author wangxl
 * @date 2019/8/16 20:19
 */
@Configuration
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.vue.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Vue接口测试")
                .description("简单优雅的restful风格")
                .termsOfServiceUrl("www.wangxianlin@icloud.com")
                .version("1.0")
                .build();
    }
}

1.3 添加注解

image.png
  • 在启动类中,需要添加一个注解


    image.png

1.4 然后启动项目

浏览器输入网址:http://127.0.0.1:8089/doc.html

image.png

  • 测试完,所有的接口没有问题了,现在我们就来编写前端的界面。

2、前端

前端,我使用的是Vue+ElementUi写的,界面简洁美观。

2.1 新建一个Vue项目

这里的话,我就不多说了,直接贴上一个链接:使用webstorm来创建并且运行vue项目详细教程

2.2 前端目录:

前端目录.png

2.3 页面与配置

2.3.1 配置

解决跨域问题:
Vue中解决跨域问题,请参照这篇文章:https://segmentfault.com/a/1190000011715088

  • 1.config/index.js
module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    // modeify
    proxyTable: {
      //modify
      '/api/**': {
        target: 'http://127.0.0.1:8089',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,//這裡true表示实现跨域
        pathRewrite: {
          '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
        }
      }
    },
  • 2.src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'

Vue.use(ElementUI)

axios.defaults.baseURL = 'http://localhost:8089/api'
// 将API方法绑定到全局
Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

2.3.2 页面 table.vue

<template>
  <el-row>
    <el-col :span="24">
      <div class="grid-content">
        <el-container>
          <el-container>
            <!--导航部分-->
            <el-header>
              <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
                <el-menu-item index="1">用户信息列表</el-menu-item>
              </el-menu>
            </el-header>
            <!--表格-->
            <el-main>
              <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="id" label="ID" width="180"></el-table-column>
                <el-table-column prop="username" label="姓名" width="180"></el-table-column>
                <el-table-column prop="sex" label="性别"></el-table-column>
                <el-table-column prop="birthday" label="生日"></el-table-column>
                <el-table-column prop="address" label="家庭住址"></el-table-column>
                <el-table-column prop="password" label="密码"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      @click="editUser(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                      type="danger"
                      @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-main>
            <el-footer>
              <el-row>
                <el-button type="primary" @click="centerDialogVisible = true">添加</el-button>
              </el-row>
            </el-footer>
          </el-container>
        </el-container>
      </div>
      <!--      添加用户-->
      <el-dialog title="添加用户" :visible.sync="centerDialogVisible" :center="true" width="50%">
        <el-form :model="form">
          <el-form-item label="姓名:" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="生日:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="请选择你的生日">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="性别:" :label-width="formLabelWidth">
            <el-select v-model="form.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="家庭住址:" :label-width="formLabelWidth">
            <el-input v-model="form.address" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码:" :label-width="formLabelWidth">
            <el-input v-model="form.password" autocomplete="off" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" :center="true">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </div>
      </el-dialog>
      <!--      修改用户-->
      <el-dialog title="修改用户" :visible.sync="editformDialogVisible" :center="true" width="50%">
        <el-form :model="editform">
          <el-input v-model="editform.id" autocomplete="off" type="hidden" ></el-input>
          <el-form-item label="姓名:" :label-width="formLabelWidth">
            <el-input v-model="editform.name" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="性别:" :label-width="formLabelWidth">
            <el-select v-model="editform.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="editform.birthday"
            type="date"
            placeholder="请选择你的生日">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="家庭住址:" :label-width="formLabelWidth">
            <el-input v-model="editform.address" autocomplete="off" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码:" :label-width="formLabelWidth">
            <el-input v-model="editform.password" autocomplete="off" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" :center="true">
          <el-button @click="editformDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser()">确 定</el-button>
        </div>
      </el-dialog>
    </el-col>
  </el-row>
</template>
<script>
  export default {
    data () {
      return {
        activeIndex: '1',
        // 表格内容
        tableData: [],
        centerDialogVisible: false,
        editformDialogVisible: false,
        //添加表单
        form: {
          name: '',
          sex: '',
          address: '',
          password: '',
          birthday:''
        },
        //修改表单
        editform: {
          id:'',
          name: '',
          sex: '',
          address: '',
          password: '',
          birthday:''
        },
        formLabelWidth: '80px'
      }
    },
    methods: {
      //添加用户
      addUser () {
        var _this = this
        _this.centerDialogVisible = false
        if (_this.form.name == '') {
          alert('姓名不能为空')
          return
        }
        if (_this.form.sex == '') {
          alert('请选择你的性别')
          return
        }
        if (_this.form.birthday == '') {
          alert('请选择你的生日')
          return
        }
        if (_this.form.address == '') {
          alert('请填写你的家庭住址')
          return
        }
        if (_this.form.password == '') {
          alert('密码不能为空')
          return
        }
        let user = JSON.stringify({
          username: _this.form.name,
          sex: _this.form.sex,
          address: _this.form.address,
          password: _this.form.password,
          birthday:_this.form.birthday
        })
        _this.$axios.post('/api/user/insertUser', user, {
          headers: {
            'Content-Type': 'application/json;charset=utf-8'  //头部信息
          }
        }).then(res => {
            if (res.data == 1) {
              _this.$message({
                message: '添加成功',
                type: 'success'
              })
              //刷新页面
              this.getData()
            }
          }
        ).catch(error => {
          _this.$message.error('添加失败,服务其内部错误')
        })
      },
      //修改用户弹窗 赋值操作
      editUser (index, row) {
        var _this = this;
        _this.editformDialogVisible=true;
        _this.editform.id = row.id;
        _this.editform.name = row.username;
        _this.editform.sex = row.sex;
        _this.editform.address = row.address;
        _this.editform.password = row.password;
        _this.editform.birthday = row.birthday;
      },
      //修改用户
      updateUser(){
        var _this = this;
        _this.editformDialogVisible=false;
        if (_this.editform.name == '') {
          alert('姓名不能为空')
          return
        }
        if (_this.editform.sex == '') {
          alert('请选择你的性别')
          return
        }
        if (_this.editform.birthday == '') {
          alert('请选择你的生日')
          return
        }
        if (_this.editform.address == '') {
          alert('请填写你的家庭住址')
          return
        }
        if (_this.editform.password == '') {
          alert('密码不能为空')
          return
        }
        let user = JSON.stringify({
          id:_this.editform.id,
          username: _this.editform.name,
          sex: _this.editform.sex,
          address: _this.editform.address,
          password: _this.editform.password,
          birthday:_this.editform.birthday
        })
        _this.$axios.post('/user/updateUser', user, {
          headers: {
            'Content-Type': 'application/json;charset=utf-8'  //头部信息
          }
        }).then(res => {
            if (res.data == 1) {
              _this.$message({
                message: '修改成功',
                type: 'success'
              })
              //刷新页面
              this.getData()
            }
          }
        ).catch(error => {
          _this.$message.error('修改失败,服务其内部错误')
          console.log(error)
        })

      },
      //删除用户
      deleteUser (index, row) {
        // index 表示当前所在行的行号
        // row  表示当前所在行的数据
        this.$confirm('是否删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var _this = this
          _this.$axios.get('/user/deleteUserById', {
            params: {
              id: row.id
            }
          }).then(res => {
              if (res.data == 1) {
                _this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                //刷新页面
                this.getData()
              }
            }
          ).catch(error => {
            _this.$message.error('删除失败,服务其内部错误')
            console.log(error)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      getData () {
        var _this = this
        _this.$axios.get('/user/quertUser', {
            params: {
              offset: 0,
              limit: 10
            }
          }
        ).then(res => {
            this.tableData = res.data
          }
        ).catch(error => {
          console.log(error)
        })
      }
    },
    mounted () {         //mounted:渲染HTML成功后调 用getData方法读取商品数据,getBrandsData读取品牌数据
      this.getData()
    }
  }
</script>
<style scoped>
</style>

3、测试

  • 用户列表


    用户列表展示.png
  • 添加用户.


    添加用户.png
  • 修改用户.


    修改用户.png
  • 删除用户


    删除用户.png
  • 删除成功


    删除成功.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容