springboot+vue實現(xiàn)登錄功能的最新方法整理
一、介紹
搜索了關(guān)于spring boot+vue的前后端分離實踐項目很多,但是對于最基礎(chǔ)登錄功能的博客卻是幾年前的了。于是學(xué)習(xí)了好幾個大神的文章后,自己通過實踐解決了vue改版等眾多問題后實現(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àn)最終項目結(jié)構(gòu)如下,方便下面步驟實現(xiàn)
2、CommonResult類
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 錯誤碼 */ 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ù)驗證失敗返回結(jié)果 */ public static <T> CommonResult<T> validateFailed() { return failed(ResultCode.VALIDATE_FAILED); } /** * 參數(shù)驗證失敗返回結(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ù)檢驗失敗"), UNAUTHORIZED(401, "暫未登錄或token已經(jīng)過期"), FORBIDDEN(403, "沒有相關(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類
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類
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、更改端口號在application.yml
Vue前端位于8080端口,后端修改到8088,不要在同一端口:
server: port: 8088
9、不同端口需要解決跨域問題
Vue端口位于8080,需要訪問8088端口服務(wù)器,需要修改CorsConfig 類,在后端處理即可。
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)全部完成,運行可以成功啟動。
四、搭建前端Vue框架
1、創(chuàng)建Vue項目
創(chuàng)建Vue項目可以使用電腦自帶cmd,也可以使用gitbush,這里我通過vscode自帶終端里面的gitbush進行創(chuàng)建。
vue create code1
(“code1”為vue項目名,可以自己設(shè)置)
(由于vue3對于以前的依賴和一些代碼的不兼容,而且目前適用范圍不是很廣,這里我就繼續(xù)選擇vue2進行操作)
創(chuàng)建完成后,進入項目并運行,檢查項目創(chuàng)建是否有誤
cd code1 npm run serve
運行成功圖如下:
瀏覽器進入已經(jīng)運行的vue項目
上面為vue2的默認(rèn)界面,可以成功進入代表創(chuàng)建項目成功,接下來便開始添加本次功能的依賴
2、添加項目依賴框架
這里可以繼續(xù)使用gitbash通過代碼進行添加,但是由于目前vue版本和依賴版本更新的有些亂,也因為我自己技術(shù)水平不夠,代碼添加的依賴經(jīng)常不兼容跑錯,于是直接使用Vue項目管理器的可視化編輯,大大提高依賴兼容成功性
2.1 使用Vue項目管理器添加依賴
進入code1項目后,使用vue ui 命令打開Vue項目管理器
vue ui
隨即會跳轉(zhuǎn)到瀏覽器,未跳轉(zhuǎn)可以自行輸入端口進入
在依賴?yán)锩嫠阉魑覀兯璧乃膫€依賴:
- element-ui,一個 element 風(fēng)格的 UI 框架
- axios,用于網(wǎng)絡(luò)請求
- Vuex,用于管理狀態(tài)
- vue-router,用于實現(xiàn)兩個 Vue 頁面的跳轉(zhuǎn)
手動添加后一般都是適應(yīng)當(dāng)前vue版本的,不用擔(dān)心兼容報錯問題
2.2 使用命令代碼添加依賴
進入code1項目后,按照下列命令依次添加依賴(由于本人學(xué)藝不精,命令添加始終無法成功運行element框架,有成功的大神希望可以評論或者私信指導(dǎo)一二,謝謝!)
vue add element npm install axios npm install vuex --save npm install vue-router
3、測試運行項目
添加成功依賴后,輸入命令npm run serve運行,出現(xiàn)如下圖界面即為成功
這里先貼圖一下最后的Vue目錄架構(gòu):
4、編寫view層面代碼
4.1 登陸頁面: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="請輸入用戶名" > <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="請輸入密碼" > <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ù)驗證不合法!"); 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 登陸成功頁面: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 登陸失敗頁面:error.vue
<template> <div> <h1>登錄錯誤:{{msg}}</h1> </div> </template> <script> export default { data() { return { msg: null }; }, created() { this.msg = this.$route.query.message; } }; </script>
5、設(shè)置路由統(tǒng)一管理頁面
5.1 創(chuàng)建路由文件
建立的 router 文件夾下創(chuàng)建一個 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)建好的路由引入到項目中
在項目的 src 目錄根節(jié)點下,找到 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è)置路由的出入口
路由還需要一個出入口,這個出入口用來告訴路由將路由的內(nèi)容顯示在這里。上面 main.js 配置的第一個 vue 顯示頁面為 App.vue ,因此我們修改 App.vue 內(nèi)容如下:
<template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App' } </script>
6、配置網(wǎng)絡(luò)請求
6.1 封裝請求工具
使用axios 這個網(wǎng)絡(luò)請求構(gòu)架進行 http 的請求,在 utils 包下封裝一個請求工具類 request.js:
import axios from 'axios' import baseUrl from '../api/baseUrl' const service = axios.create({ baseURL: baseUrl, timeout: 15000, }) export default service
6.2 登錄頁面接口 API
在 api 文件夾下,創(chuàng)建一個登錄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)建一個 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)建一個 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 引入項目,修改之前的 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')
五、實現(xiàn)登錄功能
1、啟動兩端程序,進入locallhost:8080
2、輸入賬號密碼
2.1 正確登錄
點擊登錄,進入后還會顯示登陸狀態(tài)、操作信息和狀態(tài)碼,
注意:這里修改了賬戶名為:test
2.2 錯誤登錄
總結(jié)
到此,就通過springboot+vue實現(xiàn)了最基礎(chǔ)的登錄功能。在這次學(xué)習(xí)中借鑒了Eli Shaw大神的文章,由于vue版本及其依賴更新?lián)Q代比較快,springboot也有部分更新不可用的,以前的代碼會有報錯,這篇文章希望可以提供一些幫助,有很多不足和缺點問題也希望可以提出,十分感謝!
在Github上有這個功能完整的項目:mirrors / macrozheng / mall-admin-web · GitCode
到此這篇關(guān)于springboot+vue實現(xiàn)登錄功能的文章就介紹到這了,更多相關(guān)springboot+vue登錄功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot+vue+elementsUI實現(xiàn)分角色注冊登錄界面功能
- 基于SpringBoot和Vue3的博客平臺的用戶注冊與登錄功能實現(xiàn)
- vue+springboot+shiro+jwt實現(xiàn)登錄功能
- vue+springboot實現(xiàn)登錄功能
- springboot+VUE實現(xiàn)登錄注冊
- vue+springboot實現(xiàn)登錄驗證碼
- springboot+vue實現(xiàn)登錄功能
- Vue+Jwt+SpringBoot+Ldap完成登錄認(rèn)證的示例代碼
- SpringBoot3結(jié)合Vue3實現(xiàn)用戶登錄功能
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之LinkedList的用法詳解
鏈表(Linked?list)是一種常見的基礎(chǔ)數(shù)據(jù)結(jié)構(gòu),是一種線性表。Java的LinkedList(鏈表)?類似于?ArrayList,是一種常用的數(shù)據(jù)容器,本文就來簡單講講它的使用吧2023-05-05使用Spring掃描Mybatis的mapper接口的三種配置
這篇文章主要介紹了使用Spring掃描Mybatis的mapper接口的三種配置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java利用apache ftp工具實現(xiàn)文件上傳下載和刪除功能
這篇文章主要為大家詳細(xì)介紹了Java利用apache ftp工具實現(xiàn)文件上傳下載、刪除功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06Spring Boot 整合單機websocket的步驟 附github源碼
websocket 是一個通信協(xié)議,通過單個 TCP 連接提供全雙工通信,這篇文章主要介紹了Spring Boot 整合單機websocket的步驟(附github源碼),需要的朋友可以參考下2021-10-10