SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)

目录

    • 前言
    • 一、vue-Element实现登录页面
    • 二、后端实现
    • 三、对应实现视频推荐

前言

首先我们需要用命令创建一个vue项目,这里就不详细说,因为已经写过一篇文章,关于命令创建,最好都用命令创建和安装,链接如下:
https://blog.csdn.net/weixin_39615182/article/details/115899991

最终效果展示
说明:输入账号密码,正确后,弹窗显示登录成功,跳转到首页,首页显示登录成功,欢迎您,不符合操作会有相关提示
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第1张图片
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第2张图片

SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第3张图片

前端端口:8080
后端端口:8090

一、vue-Element实现登录页面

先大致讲下实现过程,后面会推荐一个视频讲解,我就是跟着视频来的,讲的非常好

这里假设你已经创建好一个vue项目,并用IDEA打开,结构如下
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第4张图片
首先我们到ElementUI首页,来一步一步制作页面,先到它官网,组件中找到Form表单
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第5张图片
可以看到典型表单案例,点击显示代码,这个就可以复制到Login.vue中修改使用
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第6张图片
往下滑我们可以看到一个表单验证,这就可以验证输入为空,并进行提示,blur表示失去焦点,点击输入框外就是失去焦点,显示代码,然后把相关的复制过来修改
SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第7张图片
最后Login.vue代码如下

<template>
    <div class="login-box">
      <h3>欢迎登录h3>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" aria-placeholder="请输入用户名">el-input>
        el-form-item>
        <el-form-item label="密码"  prop="password">
          <el-input v-model="form.password" aria-placeholder="请输入密码" type="password">el-input>
        el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">登录el-button>
        el-form-item>
      el-form>
    div>
template>

<script>
    export default {
        name: "Login",
        //data就是对应model绑定的数据
        data(){
          return{
            form:{
              username:'',  //form.name
              password:''   //form.password
            },
            rules: {
              username: [
                {required: true, message: '请输入用户名', trigger: 'blur'},
                {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
              ],
              password: [
                {required: true, message: '请输入密码', trigger: 'blur'},
                {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
              ],
            }
          }
        },
        methods:{
          onSubmit(formName){
            this.$refs[formName].validate((valid) => {
              var vm = this;//把当前vue对象赋给vm,this表示当前vue对象,直接写this.form.username是拿不到值的,因为在axois中写this表示的是axios对象
              if (valid) {
                //发送axios请求
                this.axios({
                  method:'post',
                  url:'http://localhost:8090/login',
                  data: {
                    username:vm.form.username,
                    password:vm.form.password
                  }
                }).then(function (resp) {
                  if (resp.data.code == 0){//resp.data表示返回的数据
                    vm.$message({
                      message: '登录成功',
                      type: 'success',
                      duration:1000
                    });
                    setTimeout(function () {
                      vm.$router.push("/home") //1秒后跳转到home
                    },1200)
                  }else {
                    vm.$message.error('用户名或密码错误');
                  }
                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          }
        }
    }
script>

<style scoped>
  .login-box{
    width:500px;
    height: 300px;
    border:1px solid #DCDFE6;
    margin: 150px auto;
    padding: 20px 50px 20px 30px;
    border-radius: 20px;
    box-shadow: 0px 0px 20px #DCDFE6;
  }
style>

Home.vue代码就非常简单







router中index.js代码

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login'
import Home from '../views/Home'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: Home
    }
  ]
})

main.js中代码

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import router from './router'
import Vue from 'vue';
import App from './App.vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
import Vuex from 'vuex'


Vue.use(ElementUI);
Vue.use(VueAxios, axios);
Vue.use(Vuex);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

App.vue代码

<template>
  <div id="app">
    <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>

二、后端实现

SpringBoot+Vue+Vue-ElementUI实现登录功能(前后端分离)_第8张图片
后端比较简单,创建项目后,主要就是创建图中的几个部分

CorsConfig.java 关于跨域的配置文件

package com.yx.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("*"); //允许任何域名
        corsConfiguration.addAllowedHeader("*"); //允许任何头
        corsConfiguration.addAllowedMethod("*"); //允许任何方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); //注册
        return new CorsFilter(source);
    }
}

LoginController.java

package com.yx.controller;

import com.yx.entity.User;
import com.yx.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        System.out.println(username);
        System.out.println(password);
        //做一个假数据用于测试
        if (username.equals("xiaoming") && password.equals("123456")) {
            return Result.ok();
        }
        return Result.fail("error");
    }
}

User.java

package com.yx.entity;

public class User {

    private String username;

    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    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;
    }
}

Constants.java 常量封装工具类

package com.yx.utils;

public class Constants {

    public final static int OK_CODE = 0;    //0表示Ok

    public final static int FAIL_CODE = 400;

    public final static String OK_MSG = "请求成功";

    public final static String FAIL_MSG = "请求失败";

    public final static int STATUS_0 = 0;//可用状态

    public final static int STATUS_1 = 1;//禁用状态

    public final static String CACHE_NAME = "KACache";
}

Result.java 数据返回到前端的封装工具类

package com.yx.utils;

import java.io.Serializable;

/**
 * 数据封闭类,返回给前端
 */
public class Result implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;
    private String msg;
    private Object data; //json数据
    private Long count; // 分页信息:总条数

    public Result() {
    }

    public Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(Integer code, String msg, Object data, Long count) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.count = count;
    }

    public Integer getCode() {
        return code;
    }

    public static Result ok() {
        return new Result(Constants.OK_CODE, Constants.OK_MSG, null);
    }

    public static Result ok(Object data) {
        return new Result(Constants.OK_CODE, Constants.OK_MSG, data);
    }

    public static Result ok(String msg, long count, Object data) {
        return new Result(Constants.OK_CODE, Constants.OK_MSG, data,count);
    }

    public static Result ok(String msg, Object data) {
        return new Result(Constants.OK_CODE, msg, data);
    }

    public static Result fail(String msg) {
        return new Result(Constants.FAIL_CODE, msg, null);
    }

    public static Result fail(int errorCode, String msg) {
        return new Result(errorCode, msg, null);
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }
}

applicaion.properties只要配置一个端口即可

server.port=8090

三、对应实现视频推荐

https://www.bilibili.com/video/BV15e411W75G?p=367

你可能感兴趣的:(Java后端相关随笔,vue,java)