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

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

Project name:項(xiàng)目名稱 Project description:項(xiàng)目描述 author:作者 Runtime + Complier: 運(yùn)行時(shí)和編譯器:默認(rèn)第一個(gè) 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設(shè)置端到端測試?,選否 Should we run `npm install` for you after the project has been created?:用什么方式運(yùn)行項(xiàng)目:選npm
然后就創(chuàng)建好了,找到創(chuàng)建項(xiàng)目的路徑,cmd命令行,看package.json是dev還是serve
------------------本內(nèi)容于2022-04-11更新start-------------------------
此時(shí)的package.json文件內(nèi)容
{
"name": "項(xiàng)目名稱",
"version": "0.1.0", // b=版本
"private": true,
// 運(yùn)行腳本:serve為啟動(dòng)項(xiàng)目腳本,build為打包項(xiàng)目腳本
"scripts": {
"serve": "vue-cli-service serve --open",
"build": "vue-cli-service build"
},
// 安裝的vue依賴文件
"dependencies": {
"vue": "^2.6.11",
// vue-router一般作傳參和頁面跳轉(zhuǎn)使用
"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"
]
}
------------------本內(nèi)容于2022-04-11更新end-------------------------
運(yùn)行 npm run dev 或 npm run serve
vue ui 創(chuàng)建項(xiàng)目
這里給大家推薦第二種方式創(chuàng)建
使用cmd命令行
vue ui
會(huì)打開一個(gè)ui界面,跟著ui提示操作就行

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

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

然后新建終端,輸入運(yùn)行的命令:
------------------本內(nèi)容于2022-04-11更新start-------------------------

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

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

引入
安裝完了,你還需要引入
在mian.js里進(jìn)行引入剛剛安裝的,以及使用elementui
// 導(dǎo)入包
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')
結(jié)構(gòu)
首先看看我的學(xué)生成績管理系統(tǒng)的完整結(jié)構(gòu)

- api: 用于與后端數(shù)據(jù)交互
- assets: 用于存放靜態(tài)資源,如圖片,樣式設(shè)置
- components: 組件,一般我用它作為項(xiàng)目的主入口,即項(xiàng)目一啟動(dòng)就打開它的界面
- router: 配置路由,管理頁面跳轉(zhuǎn)
- utils: 主要工具配置,這里主要是寫axios的配置,用于引入api里的get.js和post.js,作為數(shù)據(jù)交互
- views: 你的項(xiàng)目里需要幾個(gè)頁面就使用幾個(gè)頁面進(jìn)行增添視圖組件
router配置
在以上截圖中,我有:
- Login.vue
- addScore.vue
- deleteScore.vue
- updateScore.vue
- showScore.vue
- maintry.vue
這幾個(gè)視圖組件
則,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里進(jìn)行聲明,需要在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
這個(gè)文件是axios的配置文件
代碼如下:
import axios from 'axios'
// 創(chuàng)建axios實(shí)例
// 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 // 請求超時(shí)時(shí)間
})
// 請求攔截器
axios.interceptors.request.use(
function (config) {
// 在發(fā)送請求之前做些什么
return config
},
function (error) {
// 對(duì)請求錯(cuò)誤做些什么
return Promise.reject(error)
}
)
// 響應(yīng)攔截器
axios.interceptors.response.use(
function (config) {
// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
return config
},
function (error) {
// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
return Promise.reject(error)
}
)
export default service
get和post請求
寫完request.js后,就需要根據(jù)自己的需求在get.js和post.js編寫對(duì)應(yīng)的和后端交互的代碼
以其中一個(gè)進(jìn)行舉例:
get.js:
// 導(dǎo)入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
}
})
}
如我想實(shí)現(xiàn)登錄功能,則需要先引入剛剛的request.js文件,把前端輸入框輸入的兩個(gè)參數(shù),賬號(hào)username和密碼password傳到后端,去獲取后端路徑下的/login/loginTosystem里編寫的controller方法
post.js
// 導(dǎo)入axios配置
import service from '../utils/request'
// 注冊賬號(hào)
export function registerAccount (obj) {
return service.post('/register/registerAccount', JSON.stringify(obj), {
headers: { 'Content-Type': 'application/json' }
})
}
post一般處理參數(shù)比較多的情況
如我實(shí)現(xiàn)注冊功能,用一個(gè)對(duì)象參數(shù)去接收,把它傳入后端的/register/registerAccount的controller方法
------------------本內(nèi)容于2022-04-11更新start-------------------------
// 這里給大家舉一個(gè)例子:
// 登錄和注冊界面以及功能
<template>
<div v-show="loginShowControll">
<!-- 登錄界面-->
<div v-show="loginShow" id="login_login">
<el-container>
<el-header>學(xué)生成績管理系統(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>學(xué)生成績管理系統(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: '', // 鼠標(biāo)懸停變色
registerUsername: '', // 注冊賬號(hào)
registerPassword: '' // 注冊密碼
}
},
methods: {
// 跳轉(zhuǎn)注冊界面
registerButton () {
this.loginShow = false
this.registerShow = true
},
// 登錄學(xué)生成績管理系統(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('賬號(hào)或密碼錯(cuò)誤!')
} 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
},
// 鼠標(biāo)懸停變色
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>
增刪改查的思路按照該方法去制作即可
------------------本內(nèi)容于2022-04-11更新end-------------------------
vue.config.js
這個(gè)是vue的配置文件,是代理的一種,可以理解解決跨域
module.exports = {
publicPath: '/',
lintOnSave: false,
devServer: {
disableHostCheck: true,
open: true,
port: 8080,
proxy: {
'/': {
// 連接到后端的路徑
target: 'http://localhost:8081/student',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/': '/'
}
}
}
}
}
這里有一個(gè)要注意的是,前面的module.exports一定要注意有沒有“s”如果沒有s,配置是不會(huì)生效的
vue完成
以上vue的配置基本就完成了,接下來就可以去編寫你需要的頁面和功能了
springboot
和前端不同,springboot一般使用的是依賴進(jìn)行配置所需要的內(nèi)容,以及使用注解去聲明
創(chuàng)建springboot項(xiàng)目
我使用的idea去創(chuàng)建springboot項(xiàng)目。
直接創(chuàng)建maven項(xiàng)目在后面新增文件夾作為不同的功能


直接下一步,填寫完項(xiàng)目名稱創(chuàng)建即可
依賴
本依賴為pom.xml文件的內(nèi)容
<?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驅(qū)動(dòng),mybatis等等,具體功能請百度
項(xiàng)目結(jié)構(gòu)
以我的學(xué)生成績管理系統(tǒng)為例:

- config: 配置跨域和redis配置
- constant: 配置與前端交互返回的數(shù)據(jù)提示和內(nèi)容
- controller: 控制層,接收前端的數(shù)據(jù)
- service: service層,處理接收到的數(shù)據(jù),主要作功能代碼
- dto: 實(shí)體類
- mapper: 從service到mapper,主要實(shí)現(xiàn)數(shù)據(jù)庫的增刪改查方法的實(shí)現(xiàn)
- Vo: 主要用于構(gòu)建不同數(shù)據(jù)的綜合的實(shí)體類,以及配置與前端交互的數(shù)據(jù)
- utils: 工具類,但是本項(xiàng)目并沒有用到
- resource/mapper: 數(shù)據(jù)庫的增刪改查語句
- application.yml: 配置數(shù)據(jù)庫驅(qū)動(dòng)和redis配置、服務(wù)器端口等等
- pom.xml: 依賴
- StudentScoreApplication.java: 啟動(dòng)類
ps: constant和Vo可簡化不編寫,如不編寫數(shù)據(jù)交互提示,把controller和service
層的返回?cái)?shù)據(jù)修改為別的數(shù)據(jù)類型即可,如String
啟動(dòng)類配置
想啟動(dòng)項(xiàng)目,必須要有一個(gè)入口文件,
代碼如下:
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,更新時(shí)間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) {
//設(shè)置允許跨域
registry.addMapping("/**")
.allowedOrigins("*")
// 設(shè)置允許跨域請求的域名
.allowedOriginPatterns("*")
//設(shè)置允許的方法
.allowedMethods("*")
.maxAge(3600);
}
}
數(shù)據(jù)庫配置、服務(wù)端口
application.yml 文件主要是配置數(shù)據(jù)庫和服務(wù)器的
server:
port: 8081
servlet:
# 項(xiàng)目的路徑,配置如下之后,它的路徑為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,配置了項(xiàng)目的路徑
于是本項(xiàng)目路徑為:
http:locahost:8081/student
之所以提這個(gè),因?yàn)榕履銈兒秃竺嬉v的contoller的路徑搞亂
數(shù)據(jù)交互
ps:如需要簡化,此處可不配置
主要有兩個(gè)文件,一個(gè)是ResutEnum,一個(gè)是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ù)交互響應(yīng)-提示
* */
@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運(yùn)行順序
以上,springboot的基礎(chǔ)配置就已經(jīng)ok了。
但是,在繼續(xù)往下寫代碼,我們得明白,springboot是怎么執(zhí)行代碼的。
其實(shí),我們哪怕只創(chuàng)建一個(gè)文件夾,只創(chuàng)建兩三個(gè)java文件也能編寫完一個(gè)springboot項(xiàng)目,但是,這樣的代碼是特別亂的,也不利于維護(hù);因此我們才分層,一個(gè)文件夾一個(gè)層次,每個(gè)層次處理一種類型的功能
首先,我們知道,第一步肯定是從前端接收數(shù)據(jù),那么接收到的數(shù)據(jù)第一步是哪里?
答案就是controller,別的層也可以,但是約定俗成,規(guī)定了它作為和前端交互
同理,controller接收到后,傳到了service,service編寫功能的實(shí)現(xiàn),service再請求到mapper,mappe里編寫數(shù)據(jù)庫增刪改查的實(shí)現(xiàn)
mapper再請求到resource下的mapper.xml,數(shù)據(jù)庫的增刪改查語句去查找數(shù)據(jù)庫的數(shù)據(jù)。
當(dāng)查到數(shù)據(jù)庫數(shù)據(jù)后,返回到mapper,再到service,然后回到controller,最后再返回前端。
controller層
然后我們再看controller代碼,以下所有的都以登錄和注冊功能作為例子,因?yàn)槠渌δ芏己瓦@兩個(gè)差不多
登錄是查詢
注冊是插入
登錄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/**")
代表會(huì)請求到login路徑
@GetMapping("/loginTosystem")
在login路徑下寫這個(gè)請求,代表它的路徑為
/login/loginTosystem
細(xì)心的人會(huì)發(fā)現(xiàn),前端的get和post也有寫相同的路徑
再結(jié)合配置的路徑,到請求到這里的時(shí)候,最終路徑為
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層:實(shí)體
在請求到下面的service的時(shí)候,我們應(yīng)該要有一個(gè)實(shí)體去映射,
即和數(shù)據(jù)庫字段相同,賬號(hào)表
package com.StudentScore.dto;
import lombok.Data;
/**
* @author hxc
* @dateTime: 2021-12-2
* @description: 賬號(hào)登錄注冊實(shí)體
* */
@Data
public class Account {
private String id;
// 姓名
private String name;
// 賬號(hào)
private String username;
// 密碼
private String password;
}
ps: 要注意的是,字段名稱需要一樣,否則會(huì)映射失敗,到時(shí)候拿到的數(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"代表使用自增,自增的對(duì)象是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>
結(jié)語
到此這篇關(guān)于如何搭建vue+springboot項(xiàng)目的文章就介紹到這了,更多相關(guān)vue+springboot項(xiàng)目搭建內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 運(yùn)用springboot搭建并部署web項(xiàng)目的示例
- 使用IDEA搭建一個(gè)簡單的SpringBoot項(xiàng)目超詳細(xì)過程
- 快速搭建一個(gè)SpringBoot項(xiàng)目(純小白搭建教程)
- IDEA上面搭建一個(gè)SpringBoot的web-mvc項(xiàng)目遇到的問題
- Maven搭建springboot項(xiàng)目的方法步驟
- idea快速搭建springboot項(xiàng)目的操作方法
- eclipse如何搭建Springboot項(xiàng)目詳解
- 如何利用IDEA搭建SpringBoot項(xiàng)目整合mybatis實(shí)現(xiàn)簡單的登錄功能
- 一個(gè)簡單的SpringBoot項(xiàng)目快速搭建詳細(xì)步驟
- 搭建SpringBoot項(xiàng)目三種方式(圖文教程)
相關(guān)文章
java springboot poi 從controller 接收不同類型excel 文件處理
這篇文章主要介紹了java springboot poi 從controller 接收不同類型excel 文件處理,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10
SpringBoot整合Druid數(shù)據(jù)源的方法實(shí)現(xiàn)
Druid是阿里開發(fā)的一款開源的數(shù)據(jù)源,被很多人認(rèn)為是Java語言中最好的數(shù)據(jù)庫連接池,本文主要介紹了SpringBoot整合Druid數(shù)據(jù)源的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
java內(nèi)存異常使用導(dǎo)致full?gc頻繁
Full?GC是Java虛擬機(jī)中垃圾回收的一種方式,它會(huì)暫停應(yīng)用程序所有的線程并清理整個(gè)堆內(nèi)存。頻繁的Full?GC會(huì)導(dǎo)致應(yīng)用程序的性能下降,甚至出現(xiàn)長時(shí)間的停頓。Java內(nèi)存異常使用常常是Full?GC頻繁出現(xiàn)的原因之一,如使用大量的靜態(tài)變量、內(nèi)存泄漏等。2023-04-04
深入了解Java數(shù)據(jù)結(jié)構(gòu)和算法之堆
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之堆 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01
Java使用Collections工具類對(duì)List集合進(jìn)行排序
這篇文章主要介紹了Java使用Collections工具類對(duì)List集合進(jìn)行排序,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
SpringBoot整合SpringSecurity實(shí)現(xiàn)圖形驗(yàn)證碼功能
圖形驗(yàn)證碼是一種用于區(qū)分用戶是人類還是計(jì)算機(jī)程序的自動(dòng)化測試,它通常用于防止自動(dòng)化軟件進(jìn)行惡意操作,如濫用在線服務(wù)、暴力破?解密碼或進(jìn)行垃圾郵件發(fā)送等,下面將介紹?Spring?Boot?整合?Spring?Security?實(shí)現(xiàn)圖形驗(yàn)證碼功能,需要的朋友可以參考下2024-12-12

