Home  >  Article  >  Java  >  How to build a vue+springboot project

How to build a vue+springboot project

WBOY
WBOYforward
2023-05-10 22:25:181561browse

Software used for development

  • idea: Write back-end springboot code

  • hbuilderx or VSCode to write vue code

  • Navicat or dbeaver writes and creates database tables

vue project construction

Environment configuration

Before building, you need to install it first NodeJs, I won’t go into details on how to install it, just Baidu.

cmd command

win R key to bring up the pop-up box and enter cmd to enter the console interface.

Then,

Command line

cd/d 路径地址

How to build a vue+springboot project

Switch to the path where you want to create the project

then use

vue init webpack 项目名称

Command to create the project

How to build a vue+springboot project

Project name:项目名称
Project description:项目描述
author:作者
Runtime + Complier: 运行时和编译器:默认第一个
install router :是否安装路由,选择安装就后面我安装步骤就不用执行
Use ESLint to lint your code? (Y/n):问你是否使用eslint限制语法,新手建议否
Set up unit tests (Y/n):单元测试,新手选否
Setup e2e tests with Nightwatch? (Y/n):使用Nightwatch设置端到端测试?,选否
Should we run `npm install` for you after the project has been created?:用什么方式运行项目:选npm

Then it is created, find the path to create the project, cmd command line, see whether package.json is dev or serve

The content of the package.json file at this time

{
  "name": "项目名称",
  "version": "0.1.0", // b=版本
  "private": true,
  // 运行脚本:serve为启动项目脚本,build为打包项目脚本
  "scripts": {
    "serve": "vue-cli-service serve --open",
    "build": "vue-cli-service build"
  },
  // 安装的vue依赖文件
  "dependencies": {
    "vue": "^2.6.11",
    // vue-router一般作传参和页面跳转使用
    "vue-router": "^3.5.1"
  },
  "devDependencies": {
    "@vue/cli-service": "~4.5.12",
    "vue-template-compiler": "^2.6.11"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}
运行
npm run dev
或
npm run serve

vue ui creation project

Here we recommend the second way to create

Use the cmd command line

vue ui

will open a ui interface, just follow the ui prompts

How to build a vue+springboot project

Open the web address prompted by cmd: mine is http://localhost:800

Then step by step:

How to build a vue+springboot project

ps: If the prompt is not an internal command information prompt, you need to install the vue component
Command line input: npm install vue

More specific Baidu search operations can be done

Vue project production direction sorting out

Before officially starting to run, sort out what is needed to create a vue project

After creating the vue project in the way I just did, (if you checked to install the router)

you can run the project directly through npm run serve (only the front-end part) ;

Initially it will have a component interface of HelloWorld.vue. You can see the content of the page as soon as you run it.

But these alone are not enough.

To make a fully functional vue project, you need to install at least these items:

vue-router: page jump and parameter passing

A UI framework Components: Search for the vue ui framework according to whether you need to make a computer-side or mobile-side project.
Generally, you can search for the more commonly used vue ui framework. These UI frameworks will have documents, and the documents contain the npm install command on how to install them.
This time the ui framework is elementUi

axios: currently commonly used components to interact with back-end data, because we are a vue springboot project, a project that separates the front-end and back-end
, we need to use it Connecting the front and back ends

So, by sorting it out, we will know how to proceed.

In addition, in order to quickly build a vue project, you at least need to master the following

knowledge about vue:

vue常用指令:
内容渲染指令 ————》
{{ 属性值 }}   别名:插值表达式
属性值为自定义的属性
该指令将数据渲染到页面
例子:
name: "张三" // 自定义属性
<div>{{ name }}</div>

------------------------------------------------------
属性渲染指令
v-bind:元素="属性值"  简写方式==>    :元素="属性"
------------------------------------------------------
事件渲染指令
v-on:事件名  只需要知道v-on:click="方法名" 点击事件  简写:@click="方法名"
------------------------------------------------------
双向绑定指令
v-model="属性值"
例如:给input绑定一个v-model的属性值,修改input的值,该绑定的属性值内容会跟
着改变
------------------------------------------------------
条件渲染指令
v-if
v-else-if
v-else
该指令分条件渲染页面,只有满足条件的标签才会被渲染到页面
完整写法例子:
name: "张三" // 自定义属性
// 页面写法
<div v-if="name==&#39;张三&#39;">
我的名字是张三</div> // 当满足条件时该文本会显示在页面

<div v-else>我的名字不是张三</div> // 不满足条件显示本文本内容

------------------------------------------------------

列表渲染指令
v-for=(item ,index) in list
该指令为渲染集合数组的指令,通过该指令可以把多条数据分批次渲染到界面
item为数组集合元素的内容,index为下标
例:
list: [
		{
	name: "xxx",
	age: xx,
	},
	{
	name: "zzz",
	age: zz,
	},
]
当下标为0时,item值为list下的
{
	name: "xxx",
	age:xx,
}
需要获取name属性值,则在页面中写成{{ item.name }}
完整写法例子:
<div v-for(item,index) in list>
<span>{{ item.name }}</span>
</div>
除了掌握基础指令外,还需要最起码掌握以下函数:
data() {
	return {
		// 在return这里定义自定义的属性
	}
},
// 在methods定义方法
methods: {
 方法A() {
	
	}
},
// 在created内调用方法,实现一加载页面就获取数据,用于增删改查中的查,来
查询数据
created() {
}
还需要了解:
在main.js这个入口文件引用npm install 后的组件

// 导入安装的组件
import 自定义组件名 from "组件路径(一般在搜索安装的组件文档会有说明)"
Vue.use(自定义组件名) // 引用组件(一般安装的组件文档会有说明)

例:
import Router from "./vue-router"
Vue.use(Router)

The prerequisite for mastering the above knowledge is that you After you have learned the knowledge related to HTML5, you can then start making the vue project

Open the project through the software vscode

vscode and find the project path (I use idea, it doesn’t matter what I use) The software can also be run directly with cmd)

How to build a vue+springboot project

Then create a new terminal and enter the running command:

How to build a vue+springboot project

运行
npm run dev
或
npm run serve

vue Configuration

The following vue codes are subject to vue2.x!

vue-router

vue-router is the official routing manager of vue.js. It is generally used for page jumps and parameter passing during jumps.

How to configure

Take the structure of my student management system as an example:

How to build a vue+springboot project

First, you need to introduce vue- in the interface of the vue project router,

Use the terminal of the programming software or cmd to switch to the path of your own project, and use the following code to install:

npm install vue-router

axios

axios is used for the backend Asynchronous communication, simply put, means that if you want to transfer front-end data to the back-end, you need it for data interaction

Similarly, use the terminal of the programming software or cmd to switch to the path of your own project, and use the following code to install:

npm install axios

ui framework

ui framework, as the name suggests, is used for writing interfaces, such as Taobao websites, JD.com, etc.

In fact, you can choose any one, depending on your preference. Generally, elementui, layui, museui, mintui, etc. are commonly used.

There are mobile-based ones and computer-based ones.

Take my student performance management system as an example, using elementui

Similarly, use the terminal of the programming software or cmd to switch to the path of your own project, and use the following code to install:

npm i element-ui -S

Everything needed for the basic vue project here has been installed. Open package.json and you can see the just installed

How to build a vue+springboot project

引入

安装完了,你还需要引入

在mian.js里进行引入刚刚安装的,以及使用elementui

// 导入包
import Vue from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import router from &#39;./router&#39;
import ElementUI from &#39;element-ui&#39;
import axios from &#39;axios&#39;

Vue.config.productionTip = false
// elementui
Vue.use(ElementUI)
Vue.prototype.$axios = axios

new Vue({
  el: &#39;#app&#39;,
  // 路由
  router,
  render: h => h(App),
}).$mount(&#39;#app&#39;)

结构

首先看看我的学生成绩管理系统的完整结构

How to build a vue+springboot project

  • api: 用于与后端数据交互

  • assets: 用于存放静态资源,如图片,样式设置

  • components: 组件,一般我用它作为项目的主入口,即项目一启动就打开它的界面

  • router: 配置路由,管理页面跳转

  • utils: 主要工具配置,这里主要是写axios的配置,用于引入api里的get.js和post.js,作为数据交互

  • views: 你的项目里需要几个页面就使用几个页面进行增添视图组件

router配置

在以上截图中,我有:

  • Login.vue

  • addScore.vue

  • deleteScore.vue

  • updateScore.vue

  • showScore.vue

  • maintry.vue

这几个视图组件

则,router的index.js代码如下

import Vue from &#39;vue&#39;
import Router from &#39;vue-router&#39;
import Login from &#39;@/components/Login&#39;
import maintry from &#39;@/views/maintry&#39;
import addScore from &#39;@/views/addScore&#39;
import deleteScore from &#39;@/views/deleteScore&#39;
import showScore from &#39;@/views/showScore&#39;
import updateScore from &#39;@/views/updateScore&#39;

// 挂载vue-router
// 将组件添加到router
Vue.use(Router)
export default new Router({
    routes: [
        {
            path: &#39;/&#39;,
            redirect: &#39;/login&#39;
        },
        {
            path: &#39;/login&#39;,
            name: &#39;Login&#39;,
            component: Login
        },
        {
            path: &#39;/maintry&#39;,
            name: &#39;maintry&#39;,
            component: maintry
        },
        {
            path: &#39;/addScore&#39;,
            name: &#39;addScore&#39;,
            component: addScore
        },
        {
            path: &#39;/deleteScore&#39;,
            name: &#39;deleteScore&#39;,
            component: deleteScore
        },
        {
            path: &#39;/showScore&#39;,
            name: &#39;showScore&#39;,
            component: showScore
        },
        {
            path: &#39;/updateScore&#39;,
            name: &#39;updateScore&#39;,
            component: updateScore
        }
    ]
})
ps: 需要注意的是,配置好了路由,你还需要在App.vue里进行声明,需要在App.vue
加入<router-view/>代码

App.vue代码:

<template>
  <div id="app">
      <router-view/>
  </div>
</template>

<script>

export default {
  name: &#39;app&#39;
}
</script>

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

request.js

这个文件是axios的配置文件

代码如下:

import axios from &#39;axios&#39;

// 创建axios实例
// eslint-disable-next-line no-unused-vars
const service = axios.create({
    // baseURL: &#39;/&#39;, // api的base_Url
    // 后端的请求路径
    baseURL: &#39;http://localhost:8081/student&#39;, // api的base_Url
    timeout: 50000 // 请求超时时间
})

// 请求拦截器
axios.interceptors.request.use(
    function (config) {
        // 在发送请求之前做些什么
        return config
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    function (config) {
        // 对响应数据做点什么
        return config
    },
    function (error) {
        // 对响应错误做点什么
        return Promise.reject(error)
    }
)

export default service

get和post请求

写完request.js后,就需要根据自己的需求在get.js和post.js编写对应的和后端交互的代码

以其中一个进行举例:

get.js:

// 导入axios配置
import service from &#39;../utils/request&#39;

// 登录
export function loginTosystem(username, password) {
    return service.get(&#39;/login/loginTosystem&#39;, {
        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
        params: {
            username: username,
            password: password
        }
    })
}

如我想实现登录功能,则需要先引入刚刚的request.js文件,把前端输入框输入的两个参数,账号username和密码password传到后端,去获取后端路径下的/login/loginTosystem里编写的controller方法

post.js

// 导入axios配置
import service from &#39;../utils/request&#39;

// 注册账号
export function registerAccount (obj) {
    return service.post(&#39;/register/registerAccount&#39;, JSON.stringify(obj), {
        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; }
    })
}

post一般处理参数比较多的情况

如我实现注册功能,用一个对象参数去接收,把它传入后端的/register/registerAccount的controller方法

// 这里给大家举一个例子:
// 登录和注册界面以及功能
<template>
    <div v-show="loginShowControll">
<!--        登录界面-->
        <div v-show="loginShow" id="login_login">
            <el-container>
                <el-header>学生成绩管理系统登录入口</el-header>
                <el-main>
<!--                    输入框-->
                    <span id="login_usernameInfo">用户名:</span>
                    <el-input v-model="username" placeholder="请输入用户名" id="login_input_username"></el-input>
                    <span id="login_passwordInfo">密码:</span>
                    <el-input v-model="password" placeholder="请输入密码" id="login_input_password"></el-input>
<!--                    按钮-->
                    <button type="submit" id="login_submit" @click="loginButton">登录</button>
                    <button type="submit" id="login_registerButton" @click="registerButton">注册</button>
                </el-main>
                <el-footer>登录界面</el-footer>
            </el-container>
        </div>
<!--        注册界面-->
        <div v-show="registerShow" id="login_register">
            <el-container>
                <el-header>学生成绩管理系统注册入口<span id="register_return" @click="registerReturn" @mouseover="mouseOver" @mouseleave="mouseLeave" :>返回</span></el-header>
                <el-main>
                    <!--                    输入框-->
                    <span id="register_nameInfo">姓名:</span>
                    <el-input v-model="name" placeholder="请输入姓名" id="register_input_name"></el-input>
                    <span id="register_usernameInfo">用户名:</span>
                    <el-input v-model="registerUsername" placeholder="请输入用户名" id="register_input_username"></el-input>
                    <span id="register_passwordInfo">密码:</span>
                    <el-input v-model="registerPassword" placeholder="请输入用户名" id="register_input_password"></el-input>
                    <!--                    按钮-->
                    <button type="submit" id="register_submit" @click="submitButton">提交</button>
                    <button type="submit" id="register_registerButton" @click="resetButton">重置</button>
                </el-main>
                <el-footer>注册界面</el-footer>
            </el-container>
        </div>
    </div>
</template>
<script>
    import { loginTosystem } from "../api/get";
    import { registerAccount } from "../api/post"

export default {
    name: &#39;Login&#39;,
    data () {
        return {
            loginShowControll: true, // 登录、注册界面显示控制
            loginShow: true, // 登录界面显示控制
            registerShow: false, // 注册界面显示控制
            username: &#39;&#39;, // 用户名
            password: &#39;&#39;, // 密码
            name: &#39;&#39;, // 姓名
            bgc: &#39;&#39;, // 鼠标悬停变色
            registerUsername: &#39;&#39;, // 注册账号
            registerPassword: &#39;&#39; // 注册密码
        }
    },
    methods: {
        // 跳转注册界面
        registerButton () {
            this.loginShow = false
            this.registerShow = true
        },
        // 登录学生成绩管理系统
        loginButton () {
            if (this.username.trim() == &#39;&#39;) {
                alert(&#39;请输入用户名&#39;)
                return
            }
            if (this.password.trim() == &#39;&#39;) {
                alert(&#39;请输入密码&#39;)
                return
            }
            loginTosystem(this.username, this.password).then(res => {

                if (res.data.data == null) {
                    alert(&#39;账号或密码错误!&#39;)
                } else {
                    alert(&#39;登录成功&#39;)
                    this.$router.push({
                        path: &#39;/maintry&#39;,
                        // 将username传到maintry组件,用于获取登陆人员的姓名
                        query: {username: this.username}
                    })
                }
            })
        },
        // 注册按钮
        submitButton () {
            if (this.name = &#39;&#39;) {
                alert(&#39;请输入姓名&#39;)
                return
            }
            if (this.username = &#39;&#39;) {
                alert(&#39;请输入用户名&#39;)
                return
            }
            if (this.password = &#39;&#39;) {
                alert(&#39;请输入密码&#39;)
                return
            }
            const obj = {
                username: this.registerUsername,
                password: this.registerPassword,
                name: this.name
            }
           this.registerAccount(obj)
            this.name = &#39;&#39;
            this.registerUsername = &#39;&#39;
            this.registerPassword = &#39;&#39;

        },
        // 注册信息
        async registerAccount(obj) {
            await registerAccount(obj).then(res => {
                alert(res.data.data)
            })
        },
        // 重置文本
        resetButton () {
            this.name = &#39;&#39;
            this.registerUsername = &#39;&#39;
            this.registerPassword = &#39;&#39;
        },
        // 返回登录界面
        registerReturn () {
            this.loginShow = true
            this.registerShow = false
        },
        // 鼠标悬停变色
        mouseOver () {
            this.bgc = &#39;background-color: #cccccc;color: red&#39;
        },
        mouseLeave () {
            this.bgc = &#39;&#39;
        }
    },
    watch: {
        // 监听登录和注册地方只能使用数字和英文
        username(newValue, oldValue) {
            this.username = newValue.replace(/[^A-Za-z0-9]/g, &#39;&#39;)
        },
        password(newValue, oldValue) {
            this.password = newValue.replace(/[^A-Za-z0-9]/g, &#39;&#39;)
        },
        registerUsername (newValue, oldValue) {
            this.registerUsername = newValue.replace(/[^A-Za-z0-9]/g, &#39;&#39;)
        },
        registerPassword(newValue, oldValue) {
        this.registerPassword = newValue.replace(/[^A-Za-z0-9]/g, &#39;&#39;)
    },
        // 只能输入汉字
        name(newValue,oldValue) {
            this.name = newValue.replace(/[^\4E00-\u9FA5]/g, &#39;&#39;)
        }
    }
}
</script>
<style scoped>
@import "../assets/css/login.css";
</style>

增删改查的思路按照该方法去制作即可

vue.config.js

这个是vue的配置文件,是代理的一种,可以理解解决跨域

module.exports = {
  publicPath: &#39;/&#39;,
  lintOnSave: false,
  devServer: {
    disableHostCheck: true,
    open: true,
    port: 8080,
    proxy: {
      &#39;/&#39;: {
        // 连接到后端的路径
        target: &#39;http://localhost:8081/student&#39;,
        changeOrigin: true,
        secure: false,
        pathRewrite: {
          &#39;^/&#39;: &#39;/&#39;
        }
      }
    }
  }
}

这里有一个要注意的是,前面的module.exports一定要注意有没有“s”如果没有s,配置是不会生效的

vue完成

以上vue的配置基本就完成了,接下来就可以去编写你需要的页面和功能了

springboot

和前端不同,springboot一般使用的是依赖进行配置所需要的内容,以及使用注解去声明

创建springboot项目

我使用的idea去创建springboot项目。

直接创建maven项目在后面新增文件夹作为不同的功能

How to build a vue+springboot project

How to build a vue+springboot project

直接下一步,填写完项目名称创建即可

依赖

本依赖为pom.xml文件的内容

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hxc</groupId>
    <artifactId>com.StudentScoreManage</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>
    <dependencies>
<!--        springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
<!--        fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
<!--        redis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.0</version>
        </dependency>
    </dependencies>
    <!--    编码格式-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <!--    打包配置-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

以上按需引入,引入了springboot依赖,mysql驱动,mybatis等等,具体功能请百度

项目结构

以我的学生成绩管理系统为例:

How to build a vue+springboot project

  • config: 配置跨域和redis配置

  • constant: 配置与前端交互返回的数据提示和内容

  • controller: 控制层,接收前端的数据

  • service: service层,处理接收到的数据,主要作功能代码

  • dto: 实体类

  • mapper: 从service到mapper,主要实现数据库的增删改查方法的实现

  • Vo: 主要用于构建不同数据的综合的实体类,以及配置与前端交互的数据

  • utils: 工具类,但是本项目并没有用到

  • resource/mapper: 数据库的增删改查语句

  • application.yml: 配置数据库驱动和redis配置、服务器端口等等

  • pom.xml: 依赖

  • StudentScoreApplication.java: 启动类

ps: constant和Vo可简化不编写,如不编写数据交互提示,把controller和service
层的返回数据修改为别的数据类型即可,如String

启动类配置

想启动项目,必须要有一个入口文件,

代码如下:

package com.StudentScore;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//声明springboot
@SpringBootApplication
//定义mapper区
@MapperScan("com.StudentScore.Mapper")
public class StudentScoreApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentScoreApplication.class,args);
    }
}

配置 跨域

只有配置跨域,才能接收到前端的数据请求

原本教程需要配置redis,现在简化,修改为不需要redis,更新时间2022-04-11

package com.StudentScore.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 跨域配置
 * */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域
        registry.addMapping("/**")
                .allowedOrigins("*")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                //设置允许的方法
                .allowedMethods("*")
                .maxAge(3600);
    }
}

数据库配置、服务端口

application.yml 文件主要是配置数据库和服务器的

server:
  port: 8081
  servlet:
# 项目的路径,配置如下之后,它的路径为http:locahost:8081/student
    context-path: /student
#    数据库
spring:
  datasource:
    username: root
    url: jdbc:mysql://localhost:3306/mydb
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

在这里要注意的是,context-path,配置了项目的路径

于是本项目路径为:

http:locahost:8081/student

之所以提这个,因为怕你们和后面要讲的contoller的路径搞乱

数据交互

ps:如需要简化,此处可不配置

主要有两个文件,一个是ResutEnum,一个是ResutVo

用于与前端数据交互

代码如下

package com.StudentScore.constant;

import lombok.Getter;

@Getter
public enum ResutEnum {
    OK(2000,"成功"),
    Error(5000,"失败");
    ResutEnum(Integer code,String message){
        this.code = code;
        this.message = message;
    }
    Integer code;
    String message;
}
package com.StudentScore.Vo;

import com.StudentScore.constant.ResutEnum;
import lombok.Getter;
/**
 * @author hxc
 * @dateTime: 2021-12-4
 * @description: 数据交互响应-提示
 * */
@Getter
public class ResultVo<T> {
    private T data;
    private Integer code;
    private String message;
    public ResultVo(ResutEnum resutEnum) {
        this.code = resutEnum.getCode();
        this.message = resutEnum.getMessage();
        data = null;
    }
    public ResultVo(ResutEnum resutEnum,T data) {
        this.code = resutEnum.getCode();
        this.message = resutEnum.getMessage();
        this.data = data;
    }
    public ResultVo(Integer code,String message,T data){
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

springboot运行顺序

以上,springboot的基础配置就已经ok了。

但是,在继续往下写代码,我们得明白,springboot是怎么执行代码的。

其实,我们哪怕只创建一个文件夹,只创建两三个java文件也能编写完一个springboot项目,但是,这样的代码是特别乱的,也不利于维护;因此我们才分层,一个文件夹一个层次,每个层次处理一种类型的功能

首先,我们知道,第一步肯定是从前端接收数据,那么接收到的数据第一步是哪里?

答案就是controller,别的层也可以,但是约定俗成,规定了它作为和前端交互

同理,controller接收到后,传到了service,service编写功能的实现,service再请求到mapper,mappe里编写数据库增删改查的实现

mapper再请求到resource下的mapper.xml,数据库的增删改查语句去查找数据库的数据。

当查到数据库数据后,返回到mapper,再到service,然后回到controller,最后再返回前端。

controller层

然后我们再看controller代码,以下所有的都以登录和注册功能作为例子,因为其他功能都和这两个差不多

登录是查询

注册是插入

登录controller:

package com.StudentScore.Controller;

import com.StudentScore.Service.LoginService;
import com.StudentScore.Vo.ResultVo;
import com.StudentScore.constant.ResutEnum;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 登录Controller
 * */
@RestController
@RequestMapping("/login/**")
public class LoginController {
    @Resource
    private LoginService loginService;

    // 登录到系统
    @GetMapping("/loginTosystem")
    public ResultVo loginTosystem(@RequestParam("username")String username, @RequestParam("password")String password) {
        return new ResultVo(ResutEnum.OK,loginService.loginTosystem(username,password));
    }
    @GetMapping("/findName")
    public ResultVo findName(@RequestParam("username")String username) {
        return new ResultVo(ResutEnum.OK,loginService.findName(username));
    }
}

ps: 如简化不编写数据交互,把ResultVo修改为别的类型,如String

这里需要特别说明,其他和它一样
我们看到,它@RequestMapping("/login/**")
代表会请求到login路径
    @GetMapping("/loginTosystem")
    在login路径下写这个请求,代表它的路径为
    /login/loginTosystem
    细心的人会发现,前端的get和post也有写相同的路径
    再结合配置的路径,到请求到这里的时候,最终路径为
    http:localhost:8081/student/login/loginTosystem
其他同理

注册controller:

package com.StudentScore.Controller;

import com.StudentScore.Service.RegisterService;
import com.StudentScore.Vo.ResultVo;
import com.StudentScore.constant.ResutEnum;
import com.StudentScore.dto.Account;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 注册Controller
 * */
@RestController
@RequestMapping("/register/**")
public class RegisterController {
    @Resource
    private RegisterService registerService;

    // 注册
    @PostMapping("/registerAccount")
    public ResultVo registerAccount(@RequestBody Account account) {
        return new ResultVo(ResutEnum.OK,registerService.registerAccount(account));
    }
}

ps: 如简化不编写数据交互,把ResultVo修改为别的类型,如String

dto层:实体

在请求到下面的service的时候,我们应该要有一个实体去映射,

即和数据库字段相同,账号表

package com.StudentScore.dto;

import lombok.Data;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 账号登录注册实体
 * */
@Data
public class Account {
    private String id;
    // 姓名
    private String name;
    // 账号
    private String username;
    // 密码
    private String password;
}

ps: 要注意的是,字段名称需要一样,否则会映射失败,到时候拿到的数据是空的

service层

登录service

package com.StudentScore.Service;

import com.StudentScore.Mapper.LoginMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 登录service
 * */
@Service
public class LoginService {
@Resource
    private LoginMapper loginMapper;
    // 登录
    public String loginTosystem(String username,String password){
        String message = "";
        // 判断登录的角色是否为空
        if(loginMapper.loginTosystem(username,password)== null) {
            message = "登录失败";
        }else {
            loginMapper.loginTosystem(username,password);
            message = "登录成功";
        }
       return message;
    }

    // 获取登录人员的姓名
    public String findName(String username) {
        return loginMapper.findName(username);
    }
}

注册service

package com.StudentScore.Service;

import com.StudentScore.Mapper.RegisterMapper;
import com.StudentScore.dto.Account;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author hxc
 * @dateTime:2021-12-2
 * @description: 注册service
 * */
@Service
public class RegisterService {
    @Resource
    private RegisterMapper registerMapper;

    // 注册
    public String registerAccount(Account account) {
        registerMapper.registerAccount(account);
        return "注册成功";
    }
}

mapper层

登录mapper

package com.StudentScore.Mapper;

import org.apache.ibatis.annotations.Param;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 登录mapper
 * */
public interface LoginMapper {
    // 登录
    String loginTosystem(@Param("username")String username, @Param("password")String password);
    // 获取登录的人的姓名
    String findName(@Param("username")String username);
}

注册mapper

package com.StudentScore.Mapper;

import com.StudentScore.dto.Account;
import org.apache.ibatis.annotations.Param;

/**
 * @author hxc
 * @dateTime: 2021-12-2
 * @description: 注册mapper
 * */
public interface RegisterMapper {
    // 注册
    void registerAccount(@Param("account")Account account);
}

数据库查询语句

登录:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <!-- 映射的mapper层-->
<mapper namespace="com.StudentScore.Mapper.LoginMapper">

    <select id="loginTosystem" resultType="java.lang.String">
        select username,password from scorelogin where username=#{username} and password=#{password}
    </select>
    <select id="findName" resultType="java.lang.String">
        select name from scorelogin where username=#{username}
    </select>
</mapper>

注册:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.StudentScore.Mapper.RegisterMapper">
<!--useGeneratedKeys="true" keyProperty="id"代表使用自增,自增的对象是id -->
    <insert id="registerAccount" parameterType="com.StudentScore.dto.Account" useGeneratedKeys="true" keyProperty="id">
        insert into scorelogin (name,username,password) values (#{account.name},#{account.username},#{account.password})
    </insert>
</mapper>

The above is the detailed content of How to build a vue+springboot project. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete