springboot+vue實(shí)現(xiàn)登錄功能的最新方法整理
一、介紹
搜索了關(guān)于spring boot+vue的前后端分離實(shí)踐項(xiàng)目很多,但是對(duì)于最基礎(chǔ)登錄功能的博客卻是幾年前的了。于是學(xué)習(xí)了好幾個(gè)大神的文章后,自己通過(guò)實(shí)踐解決了vue改版等眾多問(wèn)題后實(shí)現(xiàn)了登錄功能。
二、環(huán)境工具
- vue2.0
- element-ui
- axios
- vue-router
- vuex
- Java
- spring-boot
- vscode
- idea
三、搭建后端spring-boot框架
1、選擇Spring Initializr創(chuàng)建新項(xiàng)目
展現(xiàn)最終項(xiàng)目結(jié)構(gòu)如下,方便下面步驟實(shí)現(xiàn)

2、CommonResult類(lèi)
package cn.eli.vue.api;
public class CommonResult<T> {
private long code;
private String message;
private T data;
protected CommonResult() {
}
protected CommonResult(long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回結(jié)果
*
* @param data 獲取的數(shù)據(jù)
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
/**
* 成功返回結(jié)果
*
* @param data 獲取的數(shù)據(jù)
* @param message 提示信息
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
}
/**
* 失敗返回結(jié)果
*
* @param errorCode 錯(cuò)誤碼
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
}
/**
* 失敗返回結(jié)果
*
* @param message 提示信息
*/
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
}
/**
* 失敗返回結(jié)果
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCode.FAILED);
}
/**
* 參數(shù)驗(yàn)證失敗返回結(jié)果
*/
public static <T> CommonResult<T> validateFailed() {
return failed(ResultCode.VALIDATE_FAILED);
}
/**
* 參數(shù)驗(yàn)證失敗返回結(jié)果
*
* @param message 提示信息
*/
public static <T> CommonResult<T> validateFailed(String message) {
return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
}
/**
* 未登錄返回結(jié)果
*/
public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
}
/**
* 未授權(quán)返回結(jié)果
*/
public static <T> CommonResult<T> forbidden(T data) {
return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}3、IErrorCode 接口
package cn.eli.vue.api;
public interface IErrorCode {
long getCode();
String getMessage();4、ResultCode 枚舉
package cn.eli.vue.api;
public enum ResultCode implements IErrorCode {
SUCCESS(200, "操作成功"),
FAILED(500, "操作失敗"),
VALIDATE_FAILED(404, "參數(shù)檢驗(yàn)失敗"),
UNAUTHORIZED(401, "暫未登錄或token已經(jīng)過(guò)期"),
FORBIDDEN(403, "沒(méi)有相關(guān)權(quán)限");
private long code;
private String message;
private ResultCode(long code, String message) {
this.code = code;
this.message = message;
}
public long getCode() {
return code;
}
public String getMessage() {
return message;
}
}5、User類(lèi)
package cn.eli.vue.entity;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}6、LoginController類(lèi)
package cn.eli.vue.controller;
import cn.eli.vue.api.CommonResult;
import cn.eli.vue.entity.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
public CommonResult login(@RequestBody User user) {
if (user.getUsername().equals("test") && user.getPassword().equals("123456"))
return CommonResult.success("登錄成功");
else
return CommonResult.validateFailed();
}
}7、修改DemoApplication
package cn.eli.vue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}8、更改端口號(hào)在application.yml
Vue前端位于8080端口,后端修改到8088,不要在同一端口:
server: port: 8088
9、不同端口需要解決跨域問(wèn)題
Vue端口位于8080,需要訪問(wèn)8088端口服務(wù)器,需要修改CorsConfig 類(lèi),在后端處理即可。
package cn.eli.vue.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}到這里,springboot端的配置已經(jīng)全部完成,運(yùn)行可以成功啟動(dòng)。

四、搭建前端Vue框架
1、創(chuàng)建Vue項(xiàng)目
創(chuàng)建Vue項(xiàng)目可以使用電腦自帶cmd,也可以使用gitbush,這里我通過(guò)vscode自帶終端里面的gitbush進(jìn)行創(chuàng)建。
vue create code1
(“code1”為vue項(xiàng)目名,可以自己設(shè)置)

(由于vue3對(duì)于以前的依賴和一些代碼的不兼容,而且目前適用范圍不是很廣,這里我就繼續(xù)選擇vue2進(jìn)行操作)

創(chuàng)建完成后,進(jìn)入項(xiàng)目并運(yùn)行,檢查項(xiàng)目創(chuàng)建是否有誤
cd code1 npm run serve
運(yùn)行成功圖如下:

瀏覽器進(jìn)入已經(jīng)運(yùn)行的vue項(xiàng)目

上面為vue2的默認(rèn)界面,可以成功進(jìn)入代表創(chuàng)建項(xiàng)目成功,接下來(lái)便開(kāi)始添加本次功能的依賴
2、添加項(xiàng)目依賴框架
這里可以繼續(xù)使用gitbash通過(guò)代碼進(jìn)行添加,但是由于目前vue版本和依賴版本更新的有些亂,也因?yàn)槲易约杭夹g(shù)水平不夠,代碼添加的依賴經(jīng)常不兼容跑錯(cuò),于是直接使用Vue項(xiàng)目管理器的可視化編輯,大大提高依賴兼容成功性
2.1 使用Vue項(xiàng)目管理器添加依賴
進(jìn)入code1項(xiàng)目后,使用vue ui 命令打開(kāi)Vue項(xiàng)目管理器
vue ui

隨即會(huì)跳轉(zhuǎn)到瀏覽器,未跳轉(zhuǎn)可以自行輸入端口進(jìn)入

在依賴?yán)锩嫠阉魑覀兯璧乃膫€(gè)依賴:
- element-ui,一個(gè) element 風(fēng)格的 UI 框架
- axios,用于網(wǎng)絡(luò)請(qǐng)求
- Vuex,用于管理狀態(tài)
- vue-router,用于實(shí)現(xiàn)兩個(gè) Vue 頁(yè)面的跳轉(zhuǎn)

手動(dòng)添加后一般都是適應(yīng)當(dāng)前vue版本的,不用擔(dān)心兼容報(bào)錯(cuò)問(wèn)題
2.2 使用命令代碼添加依賴
進(jìn)入code1項(xiàng)目后,按照下列命令依次添加依賴(由于本人學(xué)藝不精,命令添加始終無(wú)法成功運(yùn)行element框架,有成功的大神希望可以評(píng)論或者私信指導(dǎo)一二,謝謝?。?/p>
vue add element npm install axios npm install vuex --save npm install vue-router
3、測(cè)試運(yùn)行項(xiàng)目
添加成功依賴后,輸入命令npm run serve運(yùn)行,出現(xiàn)如下圖界面即為成功

這里先貼圖一下最后的Vue目錄架構(gòu):

4、編寫(xiě)view層面代碼
4.1 登陸頁(yè)面:login.vue
<template>
<div>
<el-card class="login-form-layout">
<el-form
autocomplete="on"
:model="loginForm"
ref="loginForm"
label-position="left"
>
<div style="text-align: center">
<svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon>
</div>
<h2 class="login-title color-main">mall-admin-web</h2>
<el-form-item prop="username">
<el-input
name="username"
type="text"
v-model="loginForm.username"
autocomplete="on"
placeholder="請(qǐng)輸入用戶名"
>
<span slot="prefix">
<svg-icon icon-class="user" class="color-main"></svg-icon>
</span>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
name="password"
:type="pwdType"
@keyup.enter.native="handleLogin"
v-model="loginForm.password"
autocomplete="on"
placeholder="請(qǐng)輸入密碼"
>
<span slot="prefix">
<svg-icon icon-class="password" class="color-main"></svg-icon>
</span>
<span slot="suffix" @click="showPwd">
<svg-icon icon-class="eye" class="color-main"></svg-icon>
</span>
</el-input>
</el-form-item>
<el-form-item style="margin-bottom: 60px">
<el-button
style="width: 100%"
type="primary"
:loading="loading"
@click.native.prevent="handleLogin"
>登錄</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script>
export default {
name: "login",
data() {
return {
loginForm: {
username: "admin",
password: "123456"
},
loading: false,
pwdType: "password",
};
},
methods: {
showPwd() {
if (this.pwdType === "password") {
this.pwdType = "";
} else {
this.pwdType = "password";
}
},
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true;
this.$store
.dispatch("Login", this.loginForm)
.then(response => {
this.loading = false;
let code = response.data.code;
if (code == 200) {
this.$router.push({
path: "/success",
query: {data: response.data}
});
} else {
this.$router.push({
path: "/error",
query: { message: response.data.message }
});
}
})
.catch(() => {
this.loading = false;
});
} else {
// eslint-disable-next-line no-console
console.log("參數(shù)驗(yàn)證不合法!");
return false;
}
});
}
}
};
</script>
<style scoped>
.login-form-layout {
position: absolute;
left: 0;
right: 0;
width: 360px;
margin: 140px auto;
border-top: 10px solid #409eff;
}
.login-title {
text-align: center;
}
.login-center-layout {
background: #409eff;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
margin-top: 200px;
}
</style>4.2 登陸成功頁(yè)面:success.vue
<template>
<div>
<h1>Welcome!{{msg}}, <br>操作信息: {{mes}},<br>狀態(tài)碼{{cod}}</h1>
</div>
</template>
<script>
export default {
data() {
return {
msg: this.$route.query.data.data,
mes: this.$route.query.data.message,
cod: this.$route.query.data.code
};
},
}
</script>4.3 登陸失敗頁(yè)面:error.vue
<template>
<div>
<h1>登錄錯(cuò)誤:{{msg}}</h1>
</div>
</template>
<script>
export default {
data() {
return {
msg: null
};
},
created() {
this.msg = this.$route.query.message;
}
};
</script>5、設(shè)置路由統(tǒng)一管理頁(yè)面
5.1 創(chuàng)建路由文件
建立的 router 文件夾下創(chuàng)建一個(gè) index.js 文件,內(nèi)容如下
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);
export const constantRouterMap = [
{ path: '/', component: () => import('@/views/login')},
{ path: '/success', component: () => import('@/views/success')},
{ path: '/error', component: () => import('@/views/error'), hidden: true }
]
export default new VueRouter({
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap
})5.2 將創(chuàng)建好的路由引入到項(xiàng)目中
在項(xiàng)目的 src 目錄根節(jié)點(diǎn)下,找到 main.js,修改內(nèi)容如下:
import Vue from 'vue'
import App from './App.vue'
import './plugins/element.js'
import router from './router'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router,
}).$mount('#app')5.3 設(shè)置路由的出入口
路由還需要一個(gè)出入口,這個(gè)出入口用來(lái)告訴路由將路由的內(nèi)容顯示在這里。上面 main.js 配置的第一個(gè) vue 顯示頁(yè)面為 App.vue ,因此我們修改 App.vue 內(nèi)容如下:
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>6、配置網(wǎng)絡(luò)請(qǐng)求
6.1 封裝請(qǐng)求工具
使用axios 這個(gè)網(wǎng)絡(luò)請(qǐng)求構(gòu)架進(jìn)行 http 的請(qǐng)求,在 utils 包下封裝一個(gè)請(qǐng)求工具類(lèi) request.js:
import axios from 'axios'
import baseUrl from '../api/baseUrl'
const service = axios.create({
baseURL: baseUrl,
timeout: 15000,
})
export default service6.2 登錄頁(yè)面接口 API
在 api 文件夾下,創(chuàng)建一個(gè)登錄API文件login.js:
import request from '@/utils/request'
export function login(username, password) {
return request({
url: '/admin/login',
method: 'post',
data: {
username,
password
}
})
}6.3 封裝 axios
使用 Vuex,先封裝Vuex 中的module,在 store 文件夾下創(chuàng)建一個(gè) modules 文件夾,在此文件夾下創(chuàng)建 user.js 文件:
import { login } from '@/api/login'
const user = {
actions: {
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(response => {
commit('')
resolve(response)
}).catch(error => {
reject(error)
})
})
},
}
}
export default user創(chuàng)建 Vuex,在 store 文件夾下創(chuàng)建一個(gè) index.js 文件:
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
user
}
})將 Vuex 引入項(xiàng)目,修改之前的 main.js 文件如下:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')五、實(shí)現(xiàn)登錄功能
1、啟動(dòng)兩端程序,進(jìn)入locallhost:8080

2、輸入賬號(hào)密碼
2.1 正確登錄
點(diǎn)擊登錄,進(jìn)入后還會(huì)顯示登陸狀態(tài)、操作信息和狀態(tài)碼,
注意:這里修改了賬戶名為:test

2.2 錯(cuò)誤登錄

總結(jié)
到此,就通過(guò)springboot+vue實(shí)現(xiàn)了最基礎(chǔ)的登錄功能。在這次學(xué)習(xí)中借鑒了Eli Shaw大神的文章,由于vue版本及其依賴更新?lián)Q代比較快,springboot也有部分更新不可用的,以前的代碼會(huì)有報(bào)錯(cuò),這篇文章希望可以提供一些幫助,有很多不足和缺點(diǎn)問(wèn)題也希望可以提出,十分感謝!
在Github上有這個(gè)功能完整的項(xiàng)目:mirrors / macrozheng / mall-admin-web · GitCode
到此這篇關(guān)于springboot+vue實(shí)現(xiàn)登錄功能的文章就介紹到這了,更多相關(guān)springboot+vue登錄功能內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot+vue+elementsUI實(shí)現(xiàn)分角色注冊(cè)登錄界面功能
- 基于SpringBoot和Vue3的博客平臺(tái)的用戶注冊(cè)與登錄功能實(shí)現(xiàn)
- vue+springboot+shiro+jwt實(shí)現(xiàn)登錄功能
- vue+springboot實(shí)現(xiàn)登錄功能
- springboot+VUE實(shí)現(xiàn)登錄注冊(cè)
- vue+springboot實(shí)現(xiàn)登錄驗(yàn)證碼
- springboot+vue實(shí)現(xiàn)登錄功能
- Vue+Jwt+SpringBoot+Ldap完成登錄認(rèn)證的示例代碼
- SpringBoot3結(jié)合Vue3實(shí)現(xiàn)用戶登錄功能
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之LinkedList的用法詳解
鏈表(Linked?list)是一種常見(jiàn)的基礎(chǔ)數(shù)據(jù)結(jié)構(gòu),是一種線性表。Java的LinkedList(鏈表)?類(lèi)似于?ArrayList,是一種常用的數(shù)據(jù)容器,本文就來(lái)簡(jiǎn)單講講它的使用吧2023-05-05
使用Spring掃描Mybatis的mapper接口的三種配置
這篇文章主要介紹了使用Spring掃描Mybatis的mapper接口的三種配置,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java利用apache ftp工具實(shí)現(xiàn)文件上傳下載和刪除功能
這篇文章主要為大家詳細(xì)介紹了Java利用apache ftp工具實(shí)現(xiàn)文件上傳下載、刪除功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
Java如何實(shí)現(xiàn)壓縮文件與解壓縮zip文件
這篇文章主要介紹了Java如何實(shí)現(xiàn)壓縮文件與解壓縮zip文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Spring Boot 整合單機(jī)websocket的步驟 附github源碼
websocket 是一個(gè)通信協(xié)議,通過(guò)單個(gè) TCP 連接提供全雙工通信,這篇文章主要介紹了Spring Boot 整合單機(jī)websocket的步驟(附github源碼),需要的朋友可以參考下2021-10-10
SpringBoot過(guò)濾器與攔截器使用方法深入分析
大家應(yīng)該都曉得實(shí)現(xiàn)過(guò)濾器需要實(shí)現(xiàn) javax.servlet.Filter 接口,而攔截器會(huì)在處理指定請(qǐng)求之前和之后進(jìn)行相關(guān)操作,配置攔截器需要兩步,本文通過(guò)實(shí)例代碼給大家介紹SpringBoot 過(guò)濾器和攔截器的相關(guān)知識(shí),感興趣的朋友一起看看吧2022-12-12

