一文教會你如何搭建vue+springboot項目
前言
最近剛剛做了一個基于vue+springboot的學生成績管理系統(tǒng),于是基于這點,對遇到的一些問題進行一些配置的匯總。以及vue+springboot項目是怎么實現(xiàn)的,以下將貼出vue和springboot的重要代碼和配置。
開發(fā)使用的軟件
- idea: 編寫后端springboot代碼
- hbuilderx或VSCode編寫vue代碼
- navicat或者dbeaver 編寫創(chuàng)建數(shù)據(jù)庫表
vue項目搭建
環(huán)境配置
在搭建之前,首先你需要安裝nodeJs,具體如何安裝就不多贅述,百度即可。
cmd命令
win+R鍵喚出彈框輸入cmd,進入控制臺界面。
然后,
命令行
cd/d 路徑地址

切換到想創(chuàng)建項目的路徑
再使用
vue init webpack 項目名稱
命令創(chuàng)建項目

Project name:項目名稱 Project description:項目描述 author:作者 Runtime + Complier: 運行時和編譯器:默認第一個 install router :是否安裝路由,選擇安裝就后面我安裝步驟就不用執(zhí)行 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
然后就創(chuàng)建好了,找到創(chuàng)建項目的路徑,cmd命令行,看package.json是dev還是serve
------------------本內容于2022-04-11更新start-------------------------
此時的package.json文件內容
{
"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"
]
}
------------------本內容于2022-04-11更新end-------------------------
運行 npm run dev 或 npm run serve
vue ui 創(chuàng)建項目
這里給大家推薦第二種方式創(chuàng)建
使用cmd命令行
vue ui
會打開一個ui界面,跟著ui提示操作就行

打開cmd提示的網(wǎng)頁地址:我的是http://localhost:800
然后一步步操作:

ps:如果提示不是內部命令信息提示,就需要安裝vue組件
命令行輸入: npm install vue更具體的百度搜索操作即可
------------------本內容于2022-04-11更新start-------------------------
vue項目制作方向梳理
在正式開始運行之前先梳理一下創(chuàng)建vue項目需要什么
在按照我剛剛的方式創(chuàng)建完vue項目后,(如有勾選安裝router的情況)
便已經(jīng)可以通過npm run serve直接運行項目了,(只是有前端部分);
初始它會有一個HelloWorld.vue的組件界面。一運行便能夠看到該頁面的內容。
但是單單有這些是不夠的。
要制作一個功能齊全的vue項目,最少需要安裝這幾項:
vue-router :頁面跳轉和傳參
一個UI框架組件:根據(jù)你需要制作電腦端還是手機端項目去搜索vue ui框架。
一般都能夠搜索到比較常用的vue ui框架。這些ui框架都會有文檔,文檔內部有如何安裝
的npm install 命令。
本次的ui框架為elementUi
axios: 目前常用的與后端數(shù)據(jù)交互的組件,因為我們是vue+springboot項目,為前后端
分離的項目,需要用它來連接前后端
那么,通過梳理我們便清楚了如何往下去制作。
此外,為了快速的構建好vue項目,你最起碼你需要掌握以下關于vue的
知識:
vue常用指令:
內容渲染指令 ————》
{{ 屬性值 }} 別名:插值表達式
屬性值為自定義的屬性
該指令將數(shù)據(jù)渲染到頁面
例子:
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=='張三'">
我的名字是張三</div> // 當滿足條件時該文本會顯示在頁面
<div v-else>我的名字不是張三</div> // 不滿足條件顯示本文本內容
------------------------------------------------------
列表渲染指令
v-for=(item ,index) in list
該指令為渲染集合數(shù)組的指令,通過該指令可以把多條數(shù)據(jù)分批次渲染到界面
item為數(shù)組集合元素的內容,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>
除了掌握基礎指令外,還需要最起碼掌握以下函數(shù):
data() {
return {
// 在return這里定義自定義的屬性
}
},
// 在methods定義方法
methods: {
方法A() {
}
},
// 在created內調用方法,實現(xiàn)一加載頁面就獲取數(shù)據(jù),用于增刪改查中的查,來
查詢數(shù)據(jù)
created() {
}
還需要了解: 在main.js這個入口文件引用npm install 后的組件 // 導入安裝的組件 import 自定義組件名 from "組件路徑(一般在搜索安裝的組件文檔會有說明)" Vue.use(自定義組件名) // 引用組件(一般安裝的組件文檔會有說明) 例: import Router from "./vue-router" Vue.use(Router)
掌握了以上知識的前提,是你已經(jīng)有學習過html5相關的知識后,然后就可以著手制作vue項目了
------------------本內容于2022-04-11更新end-------------------------
通過軟件vscode打開項目
vscode,找到項目路徑(我用的是idea,無所謂用什么軟件,直接用cmd也能運行)

然后新建終端,輸入運行的命令:
------------------本內容于2022-04-11更新start-------------------------

------------------本內容于2022-04-11更新end-------------------------
運行 npm run dev 或 npm run serve
vue 配置
以下vue代碼皆以vue2.x為準!
vue-router
vue-router是vue.js的官方路由管理器,一般用它作頁面跳轉和跳轉時傳參。
如何配置
以我的學生管理系統(tǒng)的結構為例:

首先需要在vue項目的界面引入vue-router,
使用編程軟件的終端或者cmd 切換到自己項目的路徑下,使用以下代碼安裝:
npm install vue-router
axios
axios的作用用于于后端異步通信,簡單的說就是你想把前端數(shù)據(jù)傳給后端就需要它進行數(shù)據(jù)交互
同樣,使用編程軟件的終端或者cmd 切換到自己項目的路徑下,使用以下代碼安裝:
npm install axios
ui框架
ui框架,顧名思義就是用于編寫界面用的,像淘寶網(wǎng)站,京東等等。
其實選擇哪個都ok,看自己喜好,一般比較用的多的是elementui,layui,museui,和mintui等等。
有基于移動端的也有基于電腦端。
以我的學生成績管理系統(tǒng)為例,用的是elementui
同樣,使用編程軟件的終端或者cmd 切換到自己項目的路徑下,使用以下代碼安裝:
npm i element-ui -S
到這里基礎的vue項目所需要的都安裝好了,打開package.json能看到剛剛安裝的

引入
安裝完了,你還需要引入
在mian.js里進行引入剛剛安裝的,以及使用elementui
// 導入包
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import axios from 'axios'
Vue.config.productionTip = false
// elementui
Vue.use(ElementUI)
Vue.prototype.$axios = axios
new Vue({
el: '#app',
// 路由
router,
render: h => h(App),
}).$mount('#app')
結構
首先看看我的學生成績管理系統(tǒng)的完整結構

- api: 用于與后端數(shù)據(jù)交互
- assets: 用于存放靜態(tài)資源,如圖片,樣式設置
- components: 組件,一般我用它作為項目的主入口,即項目一啟動就打開它的界面
- router: 配置路由,管理頁面跳轉
- utils: 主要工具配置,這里主要是寫axios的配置,用于引入api里的get.js和post.js,作為數(shù)據(jù)交互
- views: 你的項目里需要幾個頁面就使用幾個頁面進行增添視圖組件
router配置
在以上截圖中,我有:
- Login.vue
- addScore.vue
- deleteScore.vue
- updateScore.vue
- showScore.vue
- maintry.vue
這幾個視圖組件
則,router的index.js代碼如下
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import maintry from '@/views/maintry'
import addScore from '@/views/addScore'
import deleteScore from '@/views/deleteScore'
import showScore from '@/views/showScore'
import updateScore from '@/views/updateScore'
// 掛載vue-router
// 將組件添加到router
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/maintry',
name: 'maintry',
component: maintry
},
{
path: '/addScore',
name: 'addScore',
component: addScore
},
{
path: '/deleteScore',
name: 'deleteScore',
component: deleteScore
},
{
path: '/showScore',
name: 'showScore',
component: showScore
},
{
path: '/updateScore',
name: 'updateScore',
component: updateScore
}
]
})
ps: 需要注意的是,配置好了路由,你還需要在App.vue里進行聲明,需要在App.vue 加入<router-view/>代碼
App.vue代碼:
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'app'
}
</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;
height: 100%;
}
</style>
request.js
這個文件是axios的配置文件
代碼如下:
import axios from 'axios'
// 創(chuàng)建axios實例
// eslint-disable-next-line no-unused-vars
const service = axios.create({
// baseURL: '/', // api的base_Url
// 后端的請求路徑
baseURL: 'http://localhost:8081/student', // api的base_Url
timeout: 50000 // 請求超時時間
})
// 請求攔截器
axios.interceptors.request.use(
function (config) {
// 在發(fā)送請求之前做些什么
return config
},
function (error) {
// 對請求錯誤做些什么
return Promise.reject(error)
}
)
// 響應攔截器
axios.interceptors.response.use(
function (config) {
// 對響應數(shù)據(jù)做點什么
return config
},
function (error) {
// 對響應錯誤做點什么
return Promise.reject(error)
}
)
export default service
get和post請求
寫完request.js后,就需要根據(jù)自己的需求在get.js和post.js編寫對應的和后端交互的代碼
以其中一個進行舉例:
get.js:
// 導入axios配置
import service from '../utils/request'
// 登錄
export function loginTosystem(username, password) {
return service.get('/login/loginTosystem', {
headers: { 'Content-Type': 'application/json' },
params: {
username: username,
password: password
}
})
}
如我想實現(xiàn)登錄功能,則需要先引入剛剛的request.js文件,把前端輸入框輸入的兩個參數(shù),賬號username和密碼password傳到后端,去獲取后端路徑下的/login/loginTosystem里編寫的controller方法
post.js
// 導入axios配置
import service from '../utils/request'
// 注冊賬號
export function registerAccount (obj) {
return service.post('/register/registerAccount', JSON.stringify(obj), {
headers: { 'Content-Type': 'application/json' }
})
}
post一般處理參數(shù)比較多的情況
如我實現(xiàn)注冊功能,用一個對象參數(shù)去接收,把它傳入后端的/register/registerAccount的controller方法
------------------本內容于2022-04-11更新start-------------------------
// 這里給大家舉一個例子:
// 登錄和注冊界面以及功能
<template>
<div v-show="loginShowControll">
<!-- 登錄界面-->
<div v-show="loginShow" id="login_login">
<el-container>
<el-header>學生成績管理系統(tǒng)登錄入口</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>學生成績管理系統(tǒng)注冊入口<span id="register_return" @click="registerReturn" @mouseover="mouseOver" @mouseleave="mouseLeave" :style="bgc">返回</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: 'Login',
data () {
return {
loginShowControll: true, // 登錄、注冊界面顯示控制
loginShow: true, // 登錄界面顯示控制
registerShow: false, // 注冊界面顯示控制
username: '', // 用戶名
password: '', // 密碼
name: '', // 姓名
bgc: '', // 鼠標懸停變色
registerUsername: '', // 注冊賬號
registerPassword: '' // 注冊密碼
}
},
methods: {
// 跳轉注冊界面
registerButton () {
this.loginShow = false
this.registerShow = true
},
// 登錄學生成績管理系統(tǒng)
loginButton () {
if (this.username.trim() == '') {
alert('請輸入用戶名')
return
}
if (this.password.trim() == '') {
alert('請輸入密碼')
return
}
loginTosystem(this.username, this.password).then(res => {
if (res.data.data == null) {
alert('賬號或密碼錯誤!')
} else {
alert('登錄成功')
this.$router.push({
path: '/maintry',
// 將username傳到maintry組件,用于獲取登陸人員的姓名
query: {username: this.username}
})
}
})
},
// 注冊按鈕
submitButton () {
if (this.name = '') {
alert('請輸入姓名')
return
}
if (this.username = '') {
alert('請輸入用戶名')
return
}
if (this.password = '') {
alert('請輸入密碼')
return
}
const obj = {
username: this.registerUsername,
password: this.registerPassword,
name: this.name
}
this.registerAccount(obj)
this.name = ''
this.registerUsername = ''
this.registerPassword = ''
},
// 注冊信息
async registerAccount(obj) {
await registerAccount(obj).then(res => {
alert(res.data.data)
})
},
// 重置文本
resetButton () {
this.name = ''
this.registerUsername = ''
this.registerPassword = ''
},
// 返回登錄界面
registerReturn () {
this.loginShow = true
this.registerShow = false
},
// 鼠標懸停變色
mouseOver () {
this.bgc = 'background-color: #cccccc;color: red'
},
mouseLeave () {
this.bgc = ''
}
},
watch: {
// 監(jiān)聽登錄和注冊地方只能使用數(shù)字和英文
username(newValue, oldValue) {
this.username = newValue.replace(/[^A-Za-z0-9]/g, '')
},
password(newValue, oldValue) {
this.password = newValue.replace(/[^A-Za-z0-9]/g, '')
},
registerUsername (newValue, oldValue) {
this.registerUsername = newValue.replace(/[^A-Za-z0-9]/g, '')
},
registerPassword(newValue, oldValue) {
this.registerPassword = newValue.replace(/[^A-Za-z0-9]/g, '')
},
// 只能輸入漢字
name(newValue,oldValue) {
this.name = newValue.replace(/[^\4E00-\u9FA5]/g, '')
}
}
}
</script>
<style scoped>
@import "../assets/css/login.css";
</style>
增刪改查的思路按照該方法去制作即可
------------------本內容于2022-04-11更新end-------------------------
vue.config.js
這個是vue的配置文件,是代理的一種,可以理解解決跨域
module.exports = {
publicPath: '/',
lintOnSave: false,
devServer: {
disableHostCheck: true,
open: true,
port: 8080,
proxy: {
'/': {
// 連接到后端的路徑
target: 'http://localhost:8081/student',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/': '/'
}
}
}
}
}
這里有一個要注意的是,前面的module.exports一定要注意有沒有“s”如果沒有s,配置是不會生效的
vue完成
以上vue的配置基本就完成了,接下來就可以去編寫你需要的頁面和功能了
springboot
和前端不同,springboot一般使用的是依賴進行配置所需要的內容,以及使用注解去聲明
創(chuàng)建springboot項目
我使用的idea去創(chuàng)建springboot項目。
直接創(chuàng)建maven項目在后面新增文件夾作為不同的功能


直接下一步,填寫完項目名稱創(chuàng)建即可
依賴
本依賴為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等等,具體功能請百度
項目結構
以我的學生成績管理系統(tǒng)為例:

- config: 配置跨域和redis配置
- constant: 配置與前端交互返回的數(shù)據(jù)提示和內容
- controller: 控制層,接收前端的數(shù)據(jù)
- service: service層,處理接收到的數(shù)據(jù),主要作功能代碼
- dto: 實體類
- mapper: 從service到mapper,主要實現(xiàn)數(shù)據(jù)庫的增刪改查方法的實現(xiàn)
- Vo: 主要用于構建不同數(shù)據(jù)的綜合的實體類,以及配置與前端交互的數(shù)據(jù)
- utils: 工具類,但是本項目并沒有用到
- resource/mapper: 數(shù)據(jù)庫的增刪改查語句
- application.yml: 配置數(shù)據(jù)庫驅動和redis配置、服務器端口等等
- pom.xml: 依賴
- StudentScoreApplication.java: 啟動類
ps: constant和Vo可簡化不編寫,如不編寫數(shù)據(jù)交互提示,把controller和service
層的返回數(shù)據(jù)修改為別的數(shù)據(jù)類型即可,如String
啟動類配置
想啟動項目,必須要有一個入口文件,
代碼如下:
package com.StudentScore;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//聲明springboot
@SpringBootApplication
//定義mapper區(qū)
@MapperScan("com.StudentScore.Mapper")
public class StudentScoreApplication {
public static void main(String[] args) {
SpringApplication.run(StudentScoreApplication.class,args);
}
}
配置 跨域
只有配置跨域,才能接收到前端的數(shù)據(jù)請求
原本教程需要配置redis,現(xiàn)在簡化,修改為不需要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);
}
}
數(shù)據(jù)庫配置、服務端口
application.yml 文件主要是配置數(shù)據(jù)庫和服務器的
server:
port: 8081
servlet:
# 項目的路徑,配置如下之后,它的路徑為http:locahost:8081/student
context-path: /student
# 數(shù)據(jù)庫
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的路徑搞亂
數(shù)據(jù)交互
ps:如需要簡化,此處可不配置
主要有兩個文件,一個是ResutEnum,一個是ResutVo
用于與前端數(shù)據(jù)交互
代碼如下
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: 數(shù)據(jù)交互響應-提示
* */
@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的基礎配置就已經(jīng)ok了。
但是,在繼續(xù)往下寫代碼,我們得明白,springboot是怎么執(zhí)行代碼的。
其實,我們哪怕只創(chuàng)建一個文件夾,只創(chuàng)建兩三個java文件也能編寫完一個springboot項目,但是,這樣的代碼是特別亂的,也不利于維護;因此我們才分層,一個文件夾一個層次,每個層次處理一種類型的功能
首先,我們知道,第一步肯定是從前端接收數(shù)據(jù),那么接收到的數(shù)據(jù)第一步是哪里?
答案就是controller,別的層也可以,但是約定俗成,規(guī)定了它作為和前端交互
同理,controller接收到后,傳到了service,service編寫功能的實現(xiàn),service再請求到mapper,mappe里編寫數(shù)據(jù)庫增刪改查的實現(xiàn)
mapper再請求到resource下的mapper.xml,數(shù)據(jù)庫的增刪改查語句去查找數(shù)據(jù)庫的數(shù)據(jù)。
當查到數(shù)據(jù)庫數(shù)據(jù)后,返回到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;
// 登錄到系統(tǒng)
@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: 如簡化不編寫數(shù)據(jù)交互,把ResultVo修改為別的類型,如String
這里需要特別說明,其他和它一樣
我們看到,它@RequestMapping("/login/**")
代表會請求到login路徑
@GetMapping("/loginTosystem")
在login路徑下寫這個請求,代表它的路徑為
/login/loginTosystem
細心的人會發(fā)現(xiàn),前端的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: 如簡化不編寫數(shù)據(jù)交互,把ResultVo修改為別的類型,如String
dto層:實體
在請求到下面的service的時候,我們應該要有一個實體去映射,
即和數(shù)據(jù)庫字段相同,賬號表
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: 要注意的是,字段名稱需要一樣,否則會映射失敗,到時候拿到的數(shù)據(jù)是空的
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);
}
數(shù)據(jù)庫查詢語句
登錄:
<?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>
結語
到此這篇關于如何搭建vue+springboot項目的文章就介紹到這了,更多相關vue+springboot項目搭建內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Boot 基于注解的 Redis 緩存使用詳解
本篇文章主要介紹了Spring Boot 基于注解的 Redis 緩存使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Java數(shù)據(jù)結構之加權無向圖的設計實現(xiàn)
加權無向圖是一種為每條邊關聯(lián)一個權重值或是成本的圖模型。這種圖能夠自然地表示許多應用。這篇文章主要介紹了加權無向圖的設計與實現(xiàn),感興趣的可以了解一下2022-11-11
使用Jacoco獲取 Java 程序的代碼執(zhí)行覆蓋率的步驟詳解
這篇文章主要介紹了使用Jacoco獲取 Java 程序的代碼執(zhí)行覆蓋率的步驟詳解,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下2021-03-03
SpringBoot項目中出現(xiàn)不同端口跨域問題的解決方法
這篇文章主要介紹了SpringBoot項目中出現(xiàn)不同端口跨域問題的解決方法,文中介紹了兩種解決方法,并給出了詳細的代碼供大家參考,具有一定的參考價值,需要的朋友可以參考下2024-03-03

