【笔记】Vue+Spring Boot前后端分离开发实践项目---图书管理系统

一、效果展示

主界面:

在这里插入图片描述

添加图书:

在这里插入图片描述

修改界面:

在这里插入图片描述

二、前端实现

1、Vue.cli建立项目

命令行输入vue ui(vue版本在3.0以上的UI界面)

vue ui

手动创建项目选择以下要用配置:
在这里插入图片描述
等待项目创建完成,因为也要写后端,我用idea打开(idea需要下载Vue.js扩展)在这里插入图片描述
可在终端输入

npm run serve

运行官方初始的项目,项目创建完成

2、vue+elementUI快速构建前端页面

(1)安装elementUI

打开elementUI官网
https://element.eleme.cn/#/zh-CN/component/installation
推荐用npm安装,它能更好地和 webpack 打包工具配合使用。

npm i element-ui -S

在 main.js 中写入以下内容:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
});

查看目录下package.json文件,若已经有elementUI版本号则安装成功
在这里插入图片描述

(2)使用elementUI

打开elementUI官网
https://element.eleme.cn/#/zh-CN/component/installation
找到相应组件代码,按需选取即可。
如本项目选用布局容器中的官方示例再加以修改
在这里插入图片描述
把静态页面结合vue改成动态页面,主要代码如下index.vue:

  <el-container style="height: 700px; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu router :default-openeds="['0','1']">
        <el-submenu v-for="(item,index) in $router.options.routes" :index="index+''">
          <template slot="title"><i class="el-icon-setting"></i>{{ item.name }} </template>
          <el-menu-item v-for="item2 in item.children" :index="item2.path"
                                      :class="$route.path==item2.path?'is-active':''"   v-if="item2.show">{{item2.name}}</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>
    <el-container>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>

其中<el-menu router :default-openeds="[‘0’,‘1’]>中 router 属性是和其子组件的index属性对应映射路由,:default-openeds默认打开,也是依据index属性。

其中路由管理的代码如下router/index.js:

const routes = [
  {
    path:'/',
    name:'图书管理',
    component:Index,
    redirect:'/BookManage',
    children:[
      {
        path:'/BookManage',
        name:'查询图书',
        show:true,
        component:BookManage
      },
      {
        path:'/AddBook',
        name:'添加图书',
        show:true,
        component:AddBook
      },
      {
        path:'/update',
        show:false,
        component: BookUpdate
      }
    ]
  },
]

图书管理界面BookManage.vue:

 <el-table
      :data="tableData"
      border
      style="width: 100%">
    <el-table-column
        fixed
        prop="id"
        label="编号"
        width="150">
    </el-table-column>
    <el-table-column
        prop="name"
        label="书名"
        width="600">
    </el-table-column>
    <el-table-column
        prop="author"
        label="作者"
        width="350">
    </el-table-column>
    <el-table-column
        fixed="right"
        label="操作"
        width="200">
      <template slot-scope="scope">
        <el-button @click="handleClick(scope.row)" type="text" size="small">修改</el-button>
        <el-button @click="deleteBook(scope.row)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        page-size="10"
        :total="this.total"
        @current-change="page">
    </el-pagination>

<el-pagination 是页码的组件 page-size="10"每一页多少条 :total="this.total"总页数

添加图书界面AddBook.vue:

<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="图书名称" prop="name">
      <el-input v-model="ruleForm.name" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="作者" prop="author">
      <el-input v-model="ruleForm.author" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>

修改图书界面BookUpdate.vue:

  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

    <el-form-item label="图书编号" prop="name">
      <el-input v-model="ruleForm.id" readonly style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="图书名称" prop="name">
      <el-input v-model="ruleForm.name" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item label="作者" prop="author">
      <el-input v-model="ruleForm.author" style="width: 60%"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>

(3)前端测试

前端页面并不是一开始就是动态页面,没有后端数据接口时,可以先在前端用假数据和静态页面测试,搭建好页面后再等待后端接口的实现,用Ajax获取后端数据再动态设置页面。

二、后端实现

1、用idea中Spring Initializr快速创建spring boot项目

在这里插入图片描述
选好以上依赖。Lombok中有很多方便的注解,如@Data等,DevTools实现热部署,本次项目用JPA链接MySQL。

2、编写配置文件

在这里插入图片描述
要更改端口,因为前端服务默认端口也是8080

3、准备好数据库

在这里插入图片描述

4、编写实体类

@Entity
@Data
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String author;
}

其中id设置为主键并且设置为自增。

5、Dao层

public interface BookRepository extends JpaRepository<Book,Integer> {
}

该接口只需要继承 JpaRepository 接口即可。JpaRepository
中封装了基本的数据操作方法,有基本的增删改查、分页、排序等。

6、测试

@SpringBootTest
class BookRepositoryTest {

    @Autowired
    private BookRepository bookRepository;

    @Test
    void findAll(){
        System.out.println(bookRepository.findAll());
    }

    @Test
    void save(){
        Book book =new Book();
        book.setName("springboot");
        book.setAuthor("张三");
        Book book1=bookRepository.save(book);
        System.out.println(book1);
    }

    @Test
     void findById(){
        Book book=bookRepository.findById(1).get();
        System.out.println(book);
     }

     @Test
     void update(){
        Book book=new Book();
        book.setId(18);
        book.setName("测试");
        Book book1=bookRepository.save(book);
         System.out.println(book1);
     }

     @Test
     void delete(){
        bookRepository.deleteById(18);
     }
}

分别测试crud功能,确定可用再完成接口。

7、编写Controller

简化操作省略 service 层

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Book> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
        Pageable pageable= PageRequest.of(page-1,size);
        return bookRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody Book book){
        Book result=bookRepository.save(book);
        if (result!=null){
            return "success";
        }else {
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result=bookRepository.save(book);
        if (result!=null){
            return "success";
        }else {
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);
    }
}

其中实现CRUD功能符合RESTful风格

8、解决跨域问题

由于前端8080访问后端8181构成跨域问题,此处在后端解决跨域问题,编写配置类如下:

@Configuration
public class CrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                                .allowCredentials(false)
                                .maxAge(3600)
                                .allowedHeaders("*");
    }
}

三、前后端数据联通

1、前端安装axios

首先添加axios ,命令如下:

vue add axios

项目目录多出在这里插入图片描述

2、前端连接后端接口

获取后端数据库数据,以及分页操作:

    page(currentPage){
      this.$axios.get('http://localhost:8181/book/findAll/'+currentPage+'/10').then(resp => {
        this.tableData = resp.data.content;
        this.total=resp.data.totalElements
      })
    }
  },
  created(){
    this.$axios.get('http://localhost:8181/book/findAll/1/10').then(resp => {
      this.tableData = resp.data.content;
      this.total=resp.data.totalElements
    })
  },

删除操作:

    deleteBook(row){
      this.$axios.delete('http://localhost:8181/book/deleteById/'+row.id).then(resp => {
        this.$message('删除成功!');
        window.location.reload();
      })
    }

添加操作:

 submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post('http://localhost:8181/book/save',this.ruleForm).then(resp => {
                 if(resp.data =='success'){
                   this.$message('添加成功!');
                   this.$router.push('/BookManage')
                 }
            })
          } else {
            return false;
          }
        });
      }

修改操作:

submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.put('http://localhost:8181/book/update',this.ruleForm).then(resp => {
            if(resp.data =='success'){
              this.$message('修改成功!');
              this.$router.push('/BookManage')
            }
          })
        } else {
          return false;
        }
      });
    }

以上均是部分代码

**详细代码 **

【gitee】https://gitee.com/chenyjoe/vue-SpringBoot

【github】https://github.com/chenyjoe/Vue-Spring-Boot-

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
一个完整的外卖系统,包括手机,后台管理,api 基于spring bootvue的前后分离的外卖系统 包含完整的手机,后台管理功能 技术选型 核心框架:Spring Boot 数据库层:Spring data jpa/Spring data mongodb 数据库连接池:Druid 缓存:Ehcache 前Vue.js 数据库:mysql5.5以上,Mongodb4.0(不要使用最新版4.2) 模块 flash-waimai-mobile 手机站点 flash-waimai-manage后台管理系统 flash-waimai-api java接口服务 flash-waimai-core 底层核心模块 flash-waimai-generate 代码生成模块 快速开始 数据存储采用了mysql和mongodb,其中基础管理配置功能数据使用mysql,业务数据使用mongodb存储。 创建mysql数据库 CREATE DATABASE IF NOT EXISTS waimai DEFAULT CHARSET utf8 COLLATE utf8_general_ci; CREATE USER 'waimai'@'%' IDENTIFIED BY 'waimai123'; GRANT ALL privileges ON waimai.* TO 'waimai'@'%'; flush privileges; mysql数据库创建好了之后,启动flash-waimai-api服务,会自动初始化数据,无需开发人员自己手动初始化数据 安装mongodb并创建数据库:flash-waimai 使用mongorestore命令 导入mongodb数据,由于测试数据量较大,打包放在了百度云盘:链接:https://pan.baidu.com/s/1mfO7yckFL7lMb_O0BPsviw 提取码:apgd 下载后将文件解压到d:\elm,如下命令导入数据: mongorestore.exe -d flash-waimai d:\\elm 下载项目测试数据的图片(商家和食品图片):链接:https://pan.baidu.com/s/1rvZDspoapWa6rEq2D_5kzw 提取码:urzw ,将图片存放到t_sys_cfg表中system.file.upload.path配置的目录下 启动管理平台:进入flash-waimai-manage目录:运行 npm install --registry=https://registry.npm.taobao.org运行npm run dev启动成功后访问 http://localhost:9528 ,登录,用户名密码:admin/admin 启动手机:进入flash-waimai-mobile目录:运行 npm install --registry=https://registry.npm.taobao.org运行npm run local启动成功后访问 http://localhost:8000
当然,我可以为您提供一个详细教程来帮助您部署Vue+SpringBoot前后分离项目到云服务器上使用Docker。 首先,确保您已经完成以下准备工作: - 注册一个云服务提供商的账号,并创建一个云服务器实例。 - 在本地环境中安装了Docker,并熟悉Docker的基本操作。 - 本地已经安装了Node.js和npm,以及Vue CLI和Java开发环境。 以下是详细的步骤: 1. 登录到云服务器: 使用SSH工具连接到您的云服务器。例如,使用命令行工具执行以下命令: ``` ssh username@server_ip_address ``` 2. 安装Docker: 根据您的云服务器的操作系统,选择对应的安装方式进行Docker安装。以下是一些常见操作系统的安装命令: - Ubuntu: ``` sudo apt-get update sudo apt-get install docker.io ``` - CentOS: ``` sudo yum update sudo yum install docker ``` 3. 验证Docker安装是否成功: 执行以下命令来验证Docker是否已经成功安装: ``` docker version ``` 4. 构建Vue项目: 在本地开发环境中,使用Vue CLI创建Vue项目,并进行开发和测试。确保项目可以正常运行。 ``` vue create myproject cd myproject npm run serve ``` 5. 打包Vue项目: 在Vue项目根目录下执行以下命令,将Vue项目打包成静态文件。 ``` npm run build ``` 6. 创建SpringBoot项目: 使用Spring Initializr创建SpringBoot项目,并进行开发和测试。确保项目可以正常运行。 - 访问Spring Initializr网站:https://start.spring.io/ - 选择项目的基本设置,如使用的编程语言、构建工具、Spring Boot版本等。 - 添加所需的依赖项,如Spring Web、Spring Data JPA等。 - 点击"Generate"按钮下载生成的SpringBoot项目压缩包。 - 解压缩项目压缩包,并使用您喜欢的集成开发环境(IDE)打开项目。 7. 创建Dockerfile: 在SpringBoot项目的根目录下创建一个名为`Dockerfile`的文件,用于定义Docker镜像的构建步骤。在`Dockerfile`中添加以下内容: ``` FROM openjdk:8-jdk-alpine VOLUME /tmp ADD target/myproject.jar app.jar ENTRYPOINT ["java", "-jar", "/app.jar"] ``` 8. 构建Docker镜像: 在SpringBoot项目的根目录下执行以下命令,构建Docker镜像: ``` docker build -t myproject . ``` 9. 运行Docker容器: 执行以下命令,在Docker中运行SpringBoot项目的Docker容器: ``` docker run -d -p 80:8080 myproject ``` 10. 访问应用: 使用浏览器访问您的云服务器的公网IP地址,即可查看部署好的前后分离项目。 希望这个详细教程能够帮助您成功部署Vue+SpringBoot前后分离项目到云服务器上使用Docker。如果您有任何问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChenYJoetj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值