springboot+vue實現登錄功能

本文實例為大傢分享瞭springboot+vue實現登錄功能的具體代碼,供大傢參考,具體內容如下

目錄結構

前端端口:8080
後端端口:8900

login.vue

<template>
    <div class="login_content">
        <!--  登錄塊  -->
        <div class="login_box">
            <!-- 頭像  -->
            <div class="avatar_box">
                <img src="../assets/logo.png"/>
            </div>
            <!-- 表單區域 -->
            <el-form ref="loginFormRef" :rules="loginRules"  :model="loginForm" class="login_form" label-width="0">
                <!-- 用戶名 -->
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username"  prefix-icon="iconfont icon-denglu"></el-input>
                </el-form-item>
                <!-- 密碼 -->
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password"  prefix-icon="iconfont icon-mima" type="password"></el-input>
                </el-form-item>
                <!-- 按鈕 -->
                <el-form-item class="btns">
                    <el-button type="primary" @click="login">提交</el-button>
                    <el-button type="info" @click="resetLoginFrom">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                // 表單數據
                loginForm:{
                    username:"admin",
                    password:"123456"
                },
                // 驗證對象
                loginRules:{
                    // 校驗用戶名
                    username:[
                        { required: true, message: '用戶名為必填項', trigger: 'blur' },
                        { min: 5, max: 12, message: '長度在 5 到 12 個字符', trigger: 'blur' }
                    ],
                    // 校驗密碼
                    password:[
                        { required: true, message: '用戶密碼為必填項', trigger: 'blur' },
                        { min: 6, max: 10, message: '長度在 6 - 10  個字符', trigger: 'blur' }
                    ],
                },
            }
        },
        methods:{
            // 重置表單內容
            resetLoginFrom(){
                this.$refs.loginFormRef.resetFields();
            },
            // 登錄方法
            login(){
                // 1.表單驗證
                this.$refs.loginFormRef.validate(async valid =>{
                    if(!valid){
                        return ;
                    }
                    // 表單驗證成功
                    const {data:res} = await this.$http.post("login",this.loginForm) // 訪問後臺地址
                    console.log(res)
                    if( res.flag == "ok"){
                        this.$message.success("操作成功");
                        // 跳轉到home頁面
                        this.$router.push({path:"/home"});
                        // 存儲user對象
                        window.sessionStorage.setItem("user",res.user);
                    }else{
                        this.$message.error("操作失敗")
                    }
                });
            }
        }
    }
</script>

<style lang="less" scoped>
    .login_content{
        background-color: #2b4b6b;
        height: 100%;
    }
    .login_box{
        height: 300px;
        width: 450px;
        background-color: #fff;
        border-radius: 3px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform:translate(-50%,-50%);
        .avatar_box{
            width: 130px;
            height: 130px;
            border: 1px solid #eee;
            border-radius: 50%;
            padding: 10px;
            box-shadow: 0 0 10px #ddd;
            position: absolute;
            left: 50%;
            transform:translate(-50%,-50%);
            background-color: #0ee;
            img{
                width: 100%;
                height: 100%;
                border-radius: 50%;
                background-color: #0ee;
            }
        }

    }
    .btns{
        display: flex;
        justify-content: flex-end;
    }
    .login_form{
        position: absolute;
        buttom:0%;
        width: 100%;
        padding: 0 10px;
        box-sizing: border-box;
        margin-top: 120px;
    }
</style>

Home.vue

<template>
    <div>
        <el-button type="info" @click="logout">安全退出</el-button>
    </div>
</template>
<script>
    export default {
        methods:{
            logout(){
                // 清楚session
                window.sessionStorage.clear();
                this.$router.push("/login");
            }
        }
    }
</script>
<style scoped></style>

index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
//  引入login組件
import Login from  '../components/login.vue'
import Home from  '../components/Home.vue'


Vue.use(VueRouter)

const routes = [
    {
        path:"/",
        redirect:"/login"
    },
    {
        path:"/login",
        component:Login
    },
    {
        path:"/home",
        component:Home
    },
]

const router = new VueRouter({
  routes
})
// 掛載路由導航守衛
router.beforeEach((to,from,next)=>{
    // to將要訪問
    // from 從哪訪問
    // next 接著幹next(url)重定向url上,繼續訪問to路徑
    if(to.path=='/login') return next();
    // 獲取user
    const userFlag = window.sessionStorage.getItem("user");
    // 無值返回登錄頁
    if(!userFlag) return next('/login');
    // 符合要求,放行
    next();
})
export default router

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'
// 添加全局樣式
import './assets/css/global.css'
// 引入icfont
import './assets/font/iconfont.css'

// 導入aioxs
import axios from 'axios'
// 掛載axios
Vue.prototype.$http = axios
// 設置訪問根路徑
axios.defaults.baseURL="http://localhost:9000"


Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

後臺實現

@RestController
public class LoginController {

    @Autowired
    UserDao userDao;

    @PostMapping("login")
    public String login(@RequestBody User user){
        String flag = "fail";
        User user1 = userDao.getUserByMessage(user.getUsername(),user.getPassword());
        System.out.println("user"+user1);
        if(user1!=null){
            flag="ok";
        }
        Map<String , Object> map =  new HashMap<>();
        map.put("flag",flag);
        map.put("user",user);
        String  param= JSON.toJSONString(map);
        return param;
    }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: