Springboot + Vue实现完整的登录注册功能

简介:本次实现的是一个完整的登录注册功能,其中用到的技术为Springboot+Vue+Mybatis;

在本文不再详细讲Springboot使用Mybatis进行增删改查,只展示本功能需要用到的代码;

有需要的可以查看这篇文章:实现springboot与mybatis的增删改查

前端需要引入的框架:

bootstrap是CSS框架;

axios用来进行前后端数据交互;





首先创建一个register.html

<img src="/img/P.png" width="72" height="72"> <h2 class="=form-signin0-heading">Please registh2> <input class="form-control" v-model="userName" type="text" placeholder="用户名" @blur="blur" @focus="focus" @input="userNameLimit"> <span v-html="msg">span><br> <input class="form-control" v-model="userPassword" type="password" placeholder="密码" @input="userPasswordLimit"><br> <button class="btn btn-lg btn-primary btn-block" type="button" @click="register">Registbutton> form>

在注册页面中,我们需要实现的几个功能:

1、输入注册用户名时,需要限制不允许输入特殊符号(其他限制自行考虑添加);

2、input失去焦点,判断输入框是否为空,提示“用户名不能为空”;获得焦点后,提示信息先设为空;

3、input用户名失去焦点,使用axios查看数据库中是否存在该用户名?提示用户名已存在:提示用户名可用;

4、将input密码进行MD5密码加密运算,自行选择加密的运算方式;

Java实现MD5密码加密

5、点击注册按钮,将用户名和密码添加到数据库中。


注册功能的js代码:

<script>
        var pang = new Vue({
            el:"#app",
            data:{
                userName: '',
                userPassword: '',
                msg: '',

            },
            methods:{
                // 只能输入汉字、英文、数字
                // test1:function() {
                //     this.userName = this.userName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
                // },
                //只能输入英文、数字
                userPasswordLimit:function() {
                    this.userPassword = this.userPassword.replace(/[^\a-\z\A-\Z0-9]/g, '')
                },
                // 限制输入特殊字符
                userNameLimit:function() {
                    this.userName = this.userName.replace(/[ `~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~!@#¥%……&*()——\-+={}|《》?:“”【】、;‘’,。、]/g, '')
                },

                /**
                 * 失去焦点
                 * */
                blur:function () {
                    if (this.userName.length <= 0) {
                        pang.msg = '用户名不能为空'
                    } else {
                        axios.post('/user/select',{
                            userName : this.userName,
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域
                        }).then(function (dat){
                            if (dat.data == "0"){
                                pang.msg = '用户名可用'
                            }
                            else if (dat.data == "1")
                                pang.msg = '用户名已存在'
                        })
                    }
                },
                /**
                 * 获取焦点
                 * */
                focus:function () {
                    pang.msg = null
                },

                /**
                 * 点击注册按钮事件
                 * */
                register:function () {
                    if (this.userName.length <= 0) {
                        alert("用户名不能为空")
                    } else if(this.userPassword.length <= 0) {
                        alert("密码不能为空")
                    } else {
                        axios.post('/user/addUser', {
                            userName: this.userName,
                            userPassword: this.userPassword,
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域
                        }).then(function (dat) {
                            if (dat.data == '1') {
                                window.location.href = '/user/successRegister'
                            }else {
                                alert("注册失败")
                            }

                        })
                    }

                }
            }
        })
    </script>

在登录页面中,只需判断输入的用户名和密码是否存在于数据库

在登录的时候,输入的密码也进行MD5加密,然后再与数据库中存储的数据是否相同


创建Login.html


<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>用户登录title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

    <style type="text/css">
        body {
            display:flex;
            height: 969px;
            align-items: center;
            padding:40px 0;
            background-color: #f5f5f5;
        }
        form {
            display: block;
            width: 100%;
            max-width: 330px;
            padding:15px;
            margin: auto;
        }
        .btn-block {
            width:300px;
            margin:10px auto;
        }
        .form-control {
            width:300px;
            height: 50px;
            font-size: 20px;
            margin:0 auto -20px;
            background-color: #fff;
        }


    style>
head>
<body class=text-center>

    
        <img src="/img/P.png" width="72" height="72">
        <h2 class="=form-signin0-heading">Please sign inh2>
        <input class="form-control" v-model="userName" type="text" placeholder="用户名" ><br>
        <input class="form-control" v-model="userPassword" type="password" placeholder="密码"><br>
        <button class="btn btn-lg btn-primary btn-block" type="button" @click="login" >Sign inbutton>
        <button class="btn btn-lg btn-primary btn-block" type="button" @click="register" >Go to registbutton>
    form>
    <script src="https://unpkg.com/axios/dist/axios.min.js">script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
    <script>
        new Vue({
            el:'#app',
            data:{
                userName: '',
                userPassword: ''
            },
            methods:{
                login:function () {
                    axios.post('/user/selectUserName', {
                        userName: this.userName,
                        userPassword: this.userPassword,
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域
                    }).then(function (dat) {
                        if (dat.data == '0')
                            alert("用户不存在")
                        else if (dat.data == '1')
                            alert("登录失败,账号或密码错误")
                        else if (dat.data == '2')
                        //当前窗体跳转
                            window.location.href = '/user/successLogin'
                        //新窗体跳转
                        // window.open('/user/successLogin')
                    }).catch(function () {
                        console.log("传输失败")
                    })
                },
                register:function () {
                    window.location.href = "user/register"
                }
            }
        })
    script>

body>
html>

简单的注册成功界面还有登录成功界面的html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成功注册title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js">script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
    <style>
        .btn-block {
            width:100px;
            margin:10px auto;
        }
    style>
head>
<body class="text-center">
    <div id="app">
        <h1>成功注册h1>
        <button class="btn btn-lg btn-primary btn-block" @click="Login">前往登录button>
    div>

    <script>
        new Vue({
            el:'#app',
            data:{

            },
            methods:{
                Login:function () {
                    window.location.href = "/user/login"
                }
            }
        })
    script>
body>
html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成功登录title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

head>
<body class="text-center">
    <h1 >成功登录h1>
body>
html>

在提供后端代码前,先看一下poml文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.9.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.panggroupId>
    <artifactId>flowerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>flowername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.0version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>


后端UserController.java

package com.pang.flower.Controller;

import com.pang.flower.Emtity.User;
import com.pang.flower.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/successLogin")
    public String successLogin() { return "successLogin"; }

    @RequestMapping("/successRegister")
    public String successRegister() { return "successRegister"; }

    @ResponseBody
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public String select(@RequestBody User user) {
        System.out.println(user.getUserName());
        String result = userMapper.selectUserName(user.getUserName());
        System.out.println(result);
        if (result == null) {
            return "0";
        }
        return "1";
    }


    @ResponseBody
    @RequestMapping(value = "/selectUserName", method = RequestMethod.POST)
    public String selectUserName(@RequestBody User user) {
        String userName = user.getUserName();
        String userPassword = user.getUserPassword();
        System.out.println(userName + userPassword);

        String result = "-1";

        //将输入的密码加密
        String passwordMD5 = passwordMD5(userName, userPassword);

        //用户不存在
        if (userMapper.selectUserName(userName) == null) {
//            return "用户不存在";
            result = "0";
            return result;
            //用户存在,但密码输入错误
        }else
            if(!userMapper.selectUserPassword(userName).equals(passwordMD5) ){
            result = "1";
            return result;
//            return "账号或密码输入错误";
        }else if(userMapper.selectUserPassword(userName).equals(passwordMD5)) {
            result = "2";
//            return "成功登录";
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public String addUser(@RequestBody User user) {
        String userName = user.getUserName();
        String userPassword = user.getUserPassword();
        System.out.println(userName + "***" + userPassword);
        String passwordMD5 = passwordMD5(userName, userPassword);
        userMapper.addUser(userName, passwordMD5);
        return "1";
    }

    public String passwordMD5(String userName, String userPassword) {
        // 需要加密的字符串
        String src = userName + userPassword;
        try {
            // 加密对象,指定加密方式
            MessageDigest md5 = MessageDigest.getInstance("md5");
            // 准备要加密的数据
            byte[] b = src.getBytes();
            // 加密:MD5加密一种被广泛使用的密码散列函数,
            // 可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致
            byte[] digest = md5.digest(b);
            // 十六进制的字符
            char[] chars = new char[]{'0', '1', '2', '3', '4', '5',
                    '6', '7', 'A', 'B', 'C', 'd', 'o', '*', '#', '/'};
            StringBuffer sb = new StringBuffer();
            // 处理成十六进制的字符串(通常)
            // 遍历加密后的密码,将每个元素向右位移4位,然后与15进行与运算(byte变成数字)
            for (byte bb : digest) {
                sb.append(chars[(bb >> 4) & 15]);
                sb.append(chars[bb & 15]);
            }
            // 打印加密后的字符串
            System.out.println(sb);
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

实体类User.java

package com.pang.flower.Emtity;

public class User {
    private String userName;
    private String userPassword;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
}

映射Mapper.java

package com.pang.flower.Mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {

    @Select("select userName from user where userName = #{userName}")
    public String selectUserName(String userName);

    @Select("select userPassword from user where userName = #{userName}")
    public String selectUserPassword(String userName);

    @Insert("insert into user(userName, userPassword) values(#{userName}, #{userPassword})")
    public void addUser(String userName, String userPassword);
}

界面展示

Springboot + Vue实现完整的登录注册功能_第1张图片

Springboot + Vue实现完整的登录注册功能_第2张图片

数据库界面

在这里插入图片描述

代码部分已经提供的很详细了哦,如果觉得我哪里讲的不清楚的可以评论或者私信我哦

你可能感兴趣的:(springboot)