Vue+Spring Boot簡(jiǎn)單用戶登錄(附Demo)
1 概述
前后端分離的一個(gè)簡(jiǎn)單用戶登錄 Demo 。
2 技術(shù)棧
Vue BootstrapVue Kotlin Spring Boot MyBatis Plus3 前端
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 bvdemoyarn 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 就是普通的正常 URLrouter 中的 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 = falsenew 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='http://www.lshqa.cn/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='http://www.lshqa.cn/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è)包,分別表示配置類(lèi)、控制層、持久層、實(shí)體類(lèi)、響應(yīng)類(lèi)、業(yè)務(wù)層。
4.6 實(shí)體類(lèi)
package com.example.demo.entityclass User(var username:String,var password:String)
4.7 持久層
package com.example.demo.daoimport com.baomidou.mybatisplus.core.mapper.BaseMapperimport com.example.demo.entity.Userimport org.apache.ibatis.annotations.Mapperimport org.apache.ibatis.annotations.Select@Mapperinterface 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)類(lèi),并且不需要編寫(xiě) xml 配置文件。 @Select 表示進(jìn)行查詢的 sql 語(yǔ)句。
4.8 響應(yīng)體
package com.example.demo.responseclass DemoResponse{ var data = Any() var code = 0 var message = ''}
package com.example.demo.responseclass 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 類(lèi)生成。
4.9 業(yè)務(wù)層
package com.example.demo.serviceimport com.demo.response.DemoResponseimport com.demo.response.DemoResponseBuilderimport com.example.demo.dao.DemoMapperimport com.example.demo.entity.Userimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.stereotype.Serviceimport org.springframework.transaction.annotation.Transactional@Service@Transactionalclass 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.controllerimport com.demo.response.DemoResponseimport com.example.demo.entity.Userimport com.example.demo.service.DemoServiceimport org.springframework.beans.factory.annotation.Autowiredimport 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 配置類(lèi)
package com.example.demo.configimport org.mybatis.spring.annotation.MapperScanimport org.springframework.context.annotation.Configuration@Configuration@MapperScan('com.example.demo.dao')class MyBatisConfig
@MapperScan 表示掃描對(duì)應(yīng)包下的 @Mapper 。
4.12 測(cè)試
package com.example.demoimport com.example.demo.service.DemoServiceimport org.junit.jupiter.api.Testimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.boot.test.context.SpringBootTest@SpringBootTestclass 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)類(lèi)中的 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)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. IntelliJ IDEA2020.2.2創(chuàng)建Servlet方法及404問(wèn)題2. docker /var/lib/docker/aufs/mnt 目錄清理方法3. Python的Tqdm模塊實(shí)現(xiàn)進(jìn)度條配置4. Python 多線程之threading 模塊的使用5. Python中Selenium模塊的使用詳解6. Python基于smtplib模塊發(fā)送郵件代碼實(shí)例7. CSS代碼檢查工具stylelint的使用方法詳解8. IDEA巧用Postfix Completion讓碼速起飛(小技巧)9. Python如何批量獲取文件夾的大小并保存10. CSS3中Transition屬性詳解以及示例分享
