Vue+Spring Boot簡(jiǎn)單用戶登錄(附Demo)
1 概述
前后端分離的一個(gè)簡(jiǎn)單用戶登錄 Demo 。
2 技術(shù)棧
- Vue
- BootstrapVue
- Kotlin
- Spring Boot
- MyBatis Plus
3 前端
3.1 創(chuàng)建工程
使用 vue-cli 創(chuàng)建,沒(méi)安裝的可以先安裝:
sudo cnpm install -g vue @vue/cli
查看版本:
vue -V
出現(xiàn)版本就安裝成功了。
創(chuàng)建初始工程:
vue create bvdemo
由于目前 Vue3 還沒(méi)有發(fā)布正式版本,推薦使用 Vue2 :

等待一段時(shí)間構(gòu)建好了之后會(huì)提示進(jìn)行文件夾并直接運(yùn)行:

cd bvdemo yarn serve
直接通過(guò)本地的 8080 端口即可訪問(wèn):


3.2 依賴
進(jìn)入項(xiàng)目文件夾:
cd bvdemo
安裝依賴:
cnpm install bootstrap-vue axios jquery vue-router
應(yīng)該會(huì)出現(xiàn) popper.js 過(guò)期的警告,這是 bootstrap-vue 的原因,可以忽略:

依賴說(shuō)明如下:
bootstrap-vue:一個(gè)結(jié)合了Vue與Bootstrap的前端UI框架axios是一個(gè)簡(jiǎn)潔易用高效的http庫(kù),本項(xiàng)目使用其發(fā)送登錄請(qǐng)求jquery:一個(gè)強(qiáng)大的JS庫(kù)vue-router:Vue的官方路由管理器
3.3 開(kāi)啟補(bǔ)全
在正式編寫(xiě)代碼之前開(kāi)啟對(duì) bootstrap-vue 的補(bǔ)全支持,打開(kāi)設(shè)置:

將項(xiàng)目路徑下的 node_modules 添加到庫(kù)中,把前面的勾給勾上,接著更新緩存并重啟(`File->Invalidate Cache/Restart`)。
3.4 App.vue
去掉默認(rèn)的 HelloWorld 組件,并修改 App.vue 如下:
<template>
<div id="app">
<router-view></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;
}
</style>
<router-view> 是一個(gè) functional 組件,渲染路徑匹配到的視圖組件,這里使用 <router-view> 根據(jù)訪問(wèn)路徑(路由)的不同顯示(渲染)相應(yīng)的組件。
3.5 新建 vue 組件
刪除默認(rèn)的 HelloWorld.vue ,新建 Index.vue 以及 Login.vue :

3.6 添加路由
在 main.js 同級(jí)目錄下新建 router.js ,內(nèi)容如下:
import Vue from "vue"
import VueRouter from "vue-router"
import Login from "@/components/Login"
import Index from "@/components/Index"
Vue.use(VueRouter)
const routes = [
{
path: '/',
component: Login,
props: true
},
{
path:'/index/:val',
name:'index',
component: Index,
props: true
}
]
const router = new VueRouter({
mode:'history',
routes:routes
})
export default router
routes 表示路由,其中包含了兩個(gè)路由,一個(gè)是 Login 組件的路由 / ,一個(gè)是 Index 組件的路由 /index/:val ,后者中的 :val 是占位符,用于傳遞參數(shù)。 router 表示路由器, mode 可以選擇 hash 或 history :
hash會(huì)使用URL的hash來(lái)模擬一個(gè)完整的URL,當(dāng)URL改變時(shí)頁(yè)面不會(huì)重新加載history就是普通的正常URL
router 中的 routes 參數(shù)聲明了對(duì)應(yīng)的路由,最后要記得把 router 添加到 main.js 中。
3.7 vue.config.js
在 package.json 同級(jí)目錄下創(chuàng)建 vue.config.js ,內(nèi)容如下:
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.transformAssetUrls = {
img: 'src',
image: 'xlink:href',
'b-img': 'src',
'b-img-lazy': ['src', 'blank-src'],
'b-card': 'img-src',
'b-card-img': 'src',
'b-card-img-lazy': ['src', 'blank-src'],
'b-carousel-slide': 'img-src',
'b-embed': 'src'
}
return options
})
}
}
使用該配置文件主要是因?yàn)?<b-img> 的 src 屬性不能正常讀取圖片,添加了該配置文件后即可按路徑正常讀取。
3.8 main.js
添加依賴以及路由:
import Vue from 'vue'
import App from './App.vue'
import {BootstrapVue, BootstrapVueIcons} from 'bootstrap-vue'
import router from "@/router";
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(BootstrapVue)
Vue.use(BootstrapVueIcons)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router
}).$mount('#app')
引入 BootstrapVue ,并把路由注冊(cè)到 Vue 實(shí)例中(就是倒數(shù)第2行,作為創(chuàng)建 Vue 實(shí)例的參數(shù),注意這個(gè)很重要,不然路由功能不能正常使用)。
3.9 登錄組件
也就是 Login.vue ,內(nèi)容如下:
<template>
<div>
<b-img src="../assets/logo.png"></b-img>
<br>
<b-container>
<b-row>
<b-col offset="3" cols="6">
<b-input-group size="lg">
<b-input-group-text>用戶名</b-input-group-text>
<b-form-input type="text" v-model="username"></b-form-input>
</b-input-group>
</b-col>
</b-row>
<br>
<b-row>
<b-col offset="3" cols="6">
<b-input-group size="lg">
<b-input-group-text>密碼</b-input-group-text>
<b-form-input type="password" v-model="password"></b-form-input>
</b-input-group>
</b-col>
</b-row>
<br>
<b-row>
<b-col offset="3" cols="6">
<b-button variant="success" @click="login">
一鍵注冊(cè)/登錄
</b-button>
</b-col>
</b-row>
</b-container>
</div>
</template>
<script>
import axios from 'axios'
import router from "@/router"
export default {
name: "Login.vue",
data:function (){
return{
username:'',
password:''
}
},
methods:{
login:function(){
axios.post("http://localhost:8080/login",{
username:this.username,
password:this.password
}).then(function (res){
router.push({
name:"index",
params:{
val:res.data.code === 1
}
})
})
}
}
}
</script>
<style scoped>
</style>
采用了網(wǎng)格系統(tǒng)布局 <b-row> + <b-col> ,其他組件就不說(shuō)了,大部分組件官網(wǎng)都有說(shuō)明(可以 戳這里 ),發(fā)送請(qǐng)求采用了 axios ,參數(shù)包裝在請(qǐng)求體中,注意需要與后端( @RequestBody ,寫(xiě)在請(qǐng)求頭請(qǐng)使用 @RequestParm )對(duì)應(yīng)。
另外還需要注意的是跨域問(wèn)題,這里的跨域問(wèn)題交給后端處理:
@CrossOrigin(http://localhost:8081)
(本地測(cè)試中后端運(yùn)行在 8080 端口,而前端運(yùn)行在 8081 端口)
發(fā)送請(qǐng)求后使用路由進(jìn)行跳轉(zhuǎn),攜帶的是 res.data.code 參數(shù) ,其中 res.data 是響應(yīng)中的數(shù)據(jù),后面的 code 是后端自定義的數(shù)據(jù),返回 1 表示注冊(cè)成功,返回 2 表示登錄成功。
3.10 首頁(yè)組件
首頁(yè)簡(jiǎn)單地顯示了登錄或注冊(cè)成功:
<template>
<div>
<b-img src="../assets/logo.png"></b-img>
<b-container>
<b-row align-h="center">
<b-col>
<b-jumbotron header="注冊(cè)成功" lead="歡迎" v-if="val"></b-jumbotron>
<b-jumbotron header="登錄成功" lead="歡迎" v-else></b-jumbotron>
</b-col>
</b-row>
</b-container>
</div>
</template>
<script>
export default {
name: "Index.vue",
props:['val']
}
</script>
<style scoped>
</style>
props 表示 val 是來(lái)自其他組件的參數(shù),并將其作為在 v-if 中進(jìn)行條件渲染的參數(shù)。
這樣前端就做好了。下面開(kāi)始介紹后端。
4 后端
4.1 創(chuàng)建工程
采用 Kotlin + Gradle + MyBatisPlus 構(gòu)建,新建工程如下:



4.2 依賴
引入 MyBatis Plus 依賴即可:
implementation("com.baomidou:mybatis-plus-boot-starter:3.4.0")
4.3 數(shù)據(jù)表
create database if not exists test; use test; drop table if exists user; create table user( id int auto_increment primary key , username varchar(30) default '', password varchar(30) default '' )
4.4 配置文件
數(shù)據(jù)庫(kù)用戶名+密碼+ url :
spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456
4.5 新建包
新建如下六個(gè)包,分別表示配置類、控制層、持久層、實(shí)體類、響應(yīng)類、業(yè)務(wù)層。

4.6 實(shí)體類
package com.example.demo.entity class User(var username:String,var password:String)
4.7 持久層
package com.example.demo.dao
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.example.demo.entity.User
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Select
@Mapper
interface DemoMapper :BaseMapper<User>{
@Select("select * from user where username=#{username} and password = #{password}")
fun selectByUsernameAndPassword(username:String,password:String):List<User>
}
@Mapper 表示給 Mapper 接口生成一個(gè)實(shí)現(xiàn)類,并且不需要編寫(xiě) xml 配置文件。 @Select 表示進(jìn)行查詢的 sql 語(yǔ)句。
4.8 響應(yīng)體
package com.example.demo.response
class DemoResponse
{
var data = Any()
var code = 0
var message = ""
}
package com.example.demo.response
class DemoResponseBuilder {
private var response = DemoResponse()
fun data(t:Any): DemoResponseBuilder
{
response.data = t
return this
}
fun code(t:Int): DemoResponseBuilder
{
response.code = t
return this
}
fun message(t:String): DemoResponseBuilder
{
response.message = t
return this
}
fun build() = response
}
這里響應(yīng)體分為:
- 響應(yīng)碼
- 響應(yīng)體數(shù)據(jù)
- 其他信息
與前端約定即可。生成響應(yīng)體通過(guò)一個(gè) Builder 類生成。
4.9 業(yè)務(wù)層
package com.example.demo.service
import com.demo.response.DemoResponse
import com.demo.response.DemoResponseBuilder
import com.example.demo.dao.DemoMapper
import com.example.demo.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class DemoService
{
@Autowired
lateinit var mapper: DemoMapper
fun login(username:String, password:String): DemoResponse
{
val result = mapper.selectByUsernameAndPassword(username,password).size
if(result == 0)
mapper.insert(User(username,password))
return DemoResponseBuilder().code(if(result == 0) 1 else 2).message("").data(true).build()
}
}
@Service 標(biāo)記為業(yè)務(wù)層, @Transactional 表示添加了事務(wù)管理,持久層操作失敗會(huì)進(jìn)行回滾。 @Autowired 表示自動(dòng)注入,在 Java
中可以使用直接使用 @Autowired ,而在 Kotlin 中需要使用 lateinit var 。
4.10 控制層
package com.example.demo.controller
import com.demo.response.DemoResponse
import com.example.demo.entity.User
import com.example.demo.service.DemoService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/")
@CrossOrigin("http://localhost:8081")
class DemoController {
@Autowired
lateinit var service: DemoService
@PostMapping("login")
fun login(@RequestBody user: User):DemoResponse
{
return service.login(user.username, user.password)
}
}
主要就是添加了一個(gè)跨域處理 @CrossOrigin ,開(kāi)發(fā)時(shí)請(qǐng)對(duì)應(yīng)上前端的端口。
4.11 配置類
package com.example.demo.config
import org.mybatis.spring.annotation.MapperScan
import org.springframework.context.annotation.Configuration
@Configuration
@MapperScan("com.example.demo.dao")
class MyBatisConfig
@MapperScan 表示掃描對(duì)應(yīng)包下的 @Mapper 。
4.12 測(cè)試
package com.example.demo
import com.example.demo.service.DemoService
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DemoApplicationTests {
@Autowired
lateinit var service: DemoService
@Test
fun contextLoads() {
println(service.login("123", "456"))
}
}
測(cè)試通過(guò)后后端就算完成了。
5 總測(cè)試
先運(yùn)行后端, Kotlin 不像 Java ,生成工程時(shí)能自動(dòng)配置了啟動(dòng)配置,需要手動(dòng)運(yùn)行啟動(dòng)類中的 main :

再運(yùn)行前端:
npm run serve
不想用命令行的話可以使用圖形界面配置一下:

根據(jù)控制臺(tái)輸出打開(kāi) localhost:8081 :


隨便輸入用戶名與密碼,不存在則創(chuàng)建,存在則登錄:


注冊(cè)的同時(shí)后端數(shù)據(jù)庫(kù)會(huì)生成一條記錄:

再次輸入相同的用戶名和密碼會(huì)顯示登錄成功:

這樣就正式完成了一個(gè)簡(jiǎn)單的前后端分離登錄 Demo 。
到此這篇關(guān)于Vue+Spring Boot簡(jiǎn)單用戶登錄(附Demo)的文章就介紹到這了,更多相關(guān)Vue+Spring Boot 用戶登錄 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Vue.extend 登錄注冊(cè)模態(tài)框的實(shí)現(xiàn)
- vue實(shí)現(xiàn)登錄、注冊(cè)、退出、跳轉(zhuǎn)等功能
- Vue實(shí)現(xiàn)手機(jī)號(hào)、驗(yàn)證碼登錄(60s禁用倒計(jì)時(shí))
- vue+Element-ui實(shí)現(xiàn)登錄注冊(cè)表單
- vue實(shí)現(xiàn)簡(jiǎn)單的登錄彈出框
- vue項(xiàng)目中微信登錄的實(shí)現(xiàn)操作
- Vue登錄攔截 登錄后繼續(xù)跳轉(zhuǎn)指定頁(yè)面的操作
- vue實(shí)現(xiàn)用戶長(zhǎng)時(shí)間不操作自動(dòng)退出登錄功能的實(shí)現(xiàn)代碼
- Spring Boot + Vue 前后端分離項(xiàng)目如何踢掉已登錄用戶
- vue 實(shí)現(xiàn)用戶登錄方式的切換功能
- vue實(shí)現(xiàn)登錄功能
相關(guān)文章
vue使用socket與服務(wù)端進(jìn)行通信的代碼詳解
這篇文章主要給大家介紹了vue如何使用socket與服務(wù)端進(jìn)行通信的相關(guān)資料,在Vue中我們可以將Websocket類封裝成一個(gè)Vue插件,以便全局使用,需要的朋友可以參考下2023-09-09
vue2 中使用 render 函數(shù)編寫(xiě)組件的方式
vue提供了聲明式編寫(xiě)UI的方式,即vue提供了對(duì)DOM進(jìn)行描述的方式,有兩種描述DOM的方式即模板和render 函數(shù),本文通過(guò)示例代碼介紹vue2 中使用 render 函數(shù)編寫(xiě)組件的方式,感興趣的朋友跟隨小編一起看看吧2024-06-06
vue學(xué)習(xí)筆記之過(guò)濾器的基本使用方法實(shí)例分析
這篇文章主要介紹了vue學(xué)習(xí)筆記之過(guò)濾器的基本使用方法,結(jié)合實(shí)例形式分析了vue.js過(guò)濾器的基本功能、用法與操作注意事項(xiàng),需要的朋友可以參考下2020-02-02
vant的Loading加載動(dòng)畫(huà)組件的使用(通過(guò)接口拿數(shù)據(jù)時(shí)顯示加載狀態(tài))
這篇文章主要介紹了vant的Loading加載動(dòng)畫(huà)組件的使用,通過(guò)接口拿數(shù)據(jù)時(shí)顯示加載狀態(tài),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-01-01
vue項(xiàng)目中自動(dòng)導(dǎo)入svg并愉快的使用方式
這篇文章主要介紹了vue項(xiàng)目中自動(dòng)導(dǎo)入svg并愉快的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Vue3-KeepAlive,多個(gè)頁(yè)面使用keepalive方式
這篇文章主要介紹了Vue3-KeepAlive,多個(gè)頁(yè)面使用keepalive方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

