| 作者:江夏

Part 1

目前很多公司的开发模式都是前后的分离的分工模式,这样能够做到各司其职,提高开发的效率。之前也有文章介绍了springboot项目和vue创建一个简单的前端项目,这篇文章则是将springboot和vue进行简单的整合,实现一个简单的登录页面。

最后本文的源码都会同步至github,欢迎下载使用和star!

Part 2

先介绍下本文的开发工具,后端使用的java的版本是jdk1.8,框架是springboot,开发工具是idea,前端则是使用vue.js,开发工具是vs code。

本文的前提条件是需要对springboot和vue.js 有个一定简单的了解。

一、后端Springboot项目开发:

这里先准备下数据,创建一个user表,并插入数据,sql如下:

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `email` varchar(255) NOT NULL COMMENT '邮箱',
 `password` varchar(255) NOT NULL COMMENT '密码',
 `username` varchar(255) NOT NULL COMMENT '姓名',
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


INSERT INTO `user` VALUES ('1', '1@qq.com', '123456', '张三');
INSERT INTO `user` VALUES ('2', '2@qq.com', '234567', '李四');
INSERT INTO `user` VALUES ('3', '3@qq.com', '345678', '王五');

首先创建一个springboot项目,然后在pom文件中引入相关依赖:

<?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.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>

        <!--io工具类-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!--运用SpringBoot 插件  使用spring-boot-devtools模块的应用,当classpath中的文件有改变时,会自动重启!-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties文件,添加配置内容如下:

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=jiang
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
# 配置为 com.pancm.bean 指向实体类包路径。
mybatis.typeAliasesPackage=com.springboot.bean
# 配置为 classpath 路径下 mapper 包下,* 代表会扫描所有 xml 文件。
mybatis.mapperLocations=classpath\:mapper/*.xml

开始编写核心逻辑代码:

新建一个User.java实体类,代码如下:

package com.springboot.springbootdemo.bean;
public class User {
    private long id;
    private String email;
    private String password;
    private String username;
    public long getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

然后再新建一个dao文件:

package com.springboot.springbootdemo.dao;

import com.springboot.springbootdemo.bean.User;
import org.apache.ibatis.annotations.*;
import org.springframework.data.repository.query.Param;
import java.util.List;

@Mapper
public interface UserDao {
    /**
     * 新增数据
     */
    @Insert("insert into user(id,email,password,username) values (#{id},#{email},#{password},#{username})")
    void addUser(User user);

    /**
     * 修改数据
     */
    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    void updateUser(User user);

    /**
     * 删除数据
     */
    @Delete("delete from user where id=#{id}")
    void deleteUser(int id);

    /**
     * 根据查询数据
     *
     */
    @Select("select id,email,password,username from user where username=#{userName}")
    User findByName(@Param("userName") String userName);

    /**
     * 查询所有数据
     */
    @Select("select id,email,password,username FROM user")
    List<User> findAll();
}

然后就是service和UserServiceImpl文件:

userservice:

package com.springboot.springbootdemo.service;

import com.springboot.springbootdemo.bean.User;

import java.util.List;

public interface UserService {
    /**
     * 新增用户
     * @param user
     * @return
     */
    boolean addUser(User user);

    /**
     * 修改用户
     * @param user
     * @return
     */
    boolean updateUser(User user);


    /**
     * 删除用户
     * @param id
     * @return
     */
    boolean deleteUser(int id);

    /**
     * 根据名字查询用户信息
     * @param userName
     */
    User findUserByName(String userName);


    /**
     * 查询所有数据
     * @return
     */
    List<User> findAll();
}

UserServiceImpl文件:

package com.springboot.springbootdemo.service;
import com.springboot.springbootdemo.bean.User;
import com.springboot.springbootdemo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        boolean flag=false;
        try{
            userDao.addUser(user);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean updateUser(User user) {
        boolean flag=false;
        try{
            userDao.updateUser(user);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean deleteUser(int id) {
        boolean flag=false;
        try{
            userDao.deleteUser(id);
            flag=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public User findUserByName(String userName) {
        return userDao.findByName(userName);
    }


    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}

最后就是controller文件:

package com.springboot.springbootdemo.controller;
import com.springboot.springbootdemo.bean.User;
import com.springboot.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/do/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public boolean addUser(@RequestBody User user) {
        System.out.println("新增数据:");
        return userService.addUser(user);
    }

    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public boolean updateUser(@RequestBody User user) {
        System.out.println("更新数据:");
        return userService.updateUser(user);
    }

    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    public boolean delete(@RequestParam(value = "id", required = true) int Id) {
        System.out.println("删除数据:");
        return userService.deleteUser(Id);
    }


    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {
        System.out.println("查询数据:");
        return userService.findUserByName(userName);
    }

    @RequestMapping(value = "/userAll", method = RequestMethod.GET)
    public List<User> findByUserAge() {
        System.out.println("查询所有数据:");
        return userService.findAll();
    }
}

然后启动项目,进行测试:

vue怎么整合到spring boot里 vue和springboot整合_springboot


这里后端的接口基本就开发完成了,接着开发前端的vue项目。

二、前端Vue项目开发:

这里的前端的开发是在前面提到的那篇文章的demo基础上进行开发。
先引入一些组件,在终端窗口输入下面的命令:

#引入axios
cnpm install axios --save-dev

然后在main.js文件中引入,main.js文件如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import './plugins/element.js'
//引入axios
16 import axios from 'axios'
17 Vue.prototype.$ajax = axios
Vue.config.productionTip = false

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

接着在componment文件夹下新建一个页面:

<template>
  <div class="layout">
    <Layout>
      <Content :style="{padding: '0 50px'}">
        <Card>
          <div style="min-height: 200px;">
            <v-table
              is-horizontal-resize
              style="width:100%"
              :columns="columns"
              :table-data="tableData"
              row-hover-color="#eee"
              row-click-color="#edf7ff"
            ></v-table>
          </div>
        </Card>
      </Content>
    </Layout>
  </div>
</template>

<script>
  export default {
    name: "main-page",
    data() {
      return {
        tableData: [],
        columns: [
          {field: 'id', title: '编号', width: 80, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'email', title: '邮箱', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'password', title: '密码', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'username', title: '姓名', width: 280, titleAlign: 'center', columnAlign: 'left',isResize:true}
        ]
      }
    },
    created() {
        //这里直接在created函数中使用axios的get请求向后台获取用户信息数据
        // 在实际开发中可以卸载apiadress.js中配置具体的method对应的路径和接口,这个
        //后面完善功能的情况下再进行介绍
        this.$ajax('http://localhost:8080/do/user/userAll').then(res => {
         this.tableData = res.data
          console.log(res.data);
       }).catch(function (error) {
          console.log(error);
     });
  }
  }
</script>
<style scoped>
  .layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    height: 100%;
  }
  .layout-logo{
    width: 100px;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 15px;
    left: 20px;
    font-weight: bold;
    text-align: center;
    color: #49ffcc;
  }
  .layout-nav{
    width: 420px;
    margin: 0 auto;
    margin-right: 20px;
  }
  .layout-footer-center{
    text-align: center;
  }
</style>

接着在index.js文件中加入该组件:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloDemo from '@/components/HelloDemo'
import zicomponent from '@/components/zicomponent'
import fucomponent from '@/components/fucomponent'
import MainPage from '@/components/MainPage'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path:'/hello',
      name:'HelloDemo',
      component:HelloDemo
    },
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/zi',
      name: 'zicomponent',
      component: zicomponent
    },
    {
      path: '/fu',
      name: 'fucomponent',
      component: fucomponent
    },
    {
      path: '/main',
      name: 'MainPage',
      component: MainPage
    }
  ]
})

接着输入npm run dev,编译项目:

vue怎么整合到spring boot里 vue和springboot整合_vue_02


vue怎么整合到spring boot里 vue和springboot整合_spring_03


注意这里因为vue是8081端口,而springboot项目是8080端口,所以查不出数据。

vue怎么整合到spring boot里 vue和springboot整合_vue_04


这里可以看到报跨域的错误了。所以我们要对前端的代码进行下处理:

main.js文件加入下面的代码:

vue怎么整合到spring boot里 vue和springboot整合_vue_05

// 设置全局的axios
Vue.prototype.$axios=Axios
// 设置基本路径
Axios.defaults.baseURL='/api'

config/index.js文件,在proxyTable里添加如下代码:

vue怎么整合到spring boot里 vue和springboot整合_vue_06

//代理请求路径
    proxyTable: {
      '/api':{
        target:"http://localhost:8080/",
        changeOrigin:true,
        pathRewrite:{
          '^/api':''
        }
      }
    },

vue怎么整合到spring boot里 vue和springboot整合_spring_07


最后重启下前端(我这里需要重启下不然没生效),然后编译:

vue怎么整合到spring boot里 vue和springboot整合_vue_08

Part 3

上面就是如果使用简单的将springboot和vue进行一个简单的整合