jsp登录功能的实现_springboot+mybatis+vue实现注册登录功能

2022-06-19 10:29:18

点击上方Java开发联盟,选择“星标公众号”

优质文章,第一时间送达

简介:

1. mybatis简要概述

        MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

2. vue简要概述

        Vue.js 是用于构建交互式的 Web 界面的库。它提供了 MVVM 数据绑定和一个可组合的组件系统,具有简单、灵活的 API。

3. 数据库设计

        可以使用MySQL或者Navicat设计数据库表格,为了方便测试,只用了两个简单字段用户名和密码,用户user表格设计如下:

985e82d4d53ef31a3098c54971eb179d.png

userPassword的类型原初我设计的类型是varchar,但是运行工程会报如下错误:

com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column

估计是密码字段过长了,将类型改为text即可

4. 新建SpringBoot工程

项目目录结构:

c99e6720fbb6a1488ad9c1c9152887a4.png

一、导入相关包——POM配置,这里需要加入的依赖有:Spring Web,Spring Data JDBC,MySQL Driver、MyBatis Framework。

<?xml version="1.0" encoding="UTF-8"?><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.3.2.RELEASEversion>    <relativePath/>   parent>  <groupId>com.example.demo2groupId>  <artifactId>demo2artifactId>  <version>0.0.1-SNAPSHOTversion>  <name>demo2name>  <description>Demo project for Spring Bootdescription>  <properties>    <java.version>1.8java.version>  properties>  <dependencies>    <dependency>      <groupId>org.springframework.bootgroupId>      <artifactId>spring-boot-starter-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.3version>    dependency>    <dependency>      <groupId>mysqlgroupId>      <artifactId>mysql-connector-javaartifactId>      <scope>runtimescope>    dependency>    <dependency>      <groupId>org.springframework.bootgroupId>      <artifactId>spring-boot-starter-testartifactId>      <scope>testscope>      <exclusions>        <exclusion>          <groupId>org.junit.vintagegroupId>          <artifactId>junit-vintage-engineartifactId>        exclusion>      exclusions>    dependency>  dependencies>  <build>    <plugins>      <plugin>        <groupId>org.springframework.bootgroupId>        <artifactId>spring-boot-maven-pluginartifactId>      plugin>    plugins>  build>project>

4.1、配置文件——数据库相关配置

1、application.yml文件

server:  port: 8080  tomcat:    uri-encoding: utf-8spring:  datasource:    driver-class-name: com.mysql.cj.jdbc.Driver    url: jdbc:mysql://localhost:3306/myweb?serverTimezone=UTC&useSSL=false    username: root    password: 123456  resources:    static-locations: classpath:/templates

这里的数据库地址一定要填写正确,还有就是你连接数据库的用户名和密码!

4.2、实体类User.java

package com.example.simole.Bean;public class User {    private String UserName;    private String Password;    public String getUserName() {        return UserName;    }    public void setUserName(String userName) {        UserName = userName;    }    public String getPassword() {        return Password;    }    public void setPassword(String password) {        Password = password;    }}

4.3、映射类UserMapper.java

package com.example.demo1.Mapper;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Select;@Mapperpublic 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);}

注意上面的sql语句,userName和userPassword都是我设计的字段,请根据自己设计的字段修改。

4.4、服务层UserService.java

package com.example.demo1.Service;import com.example.demo1.Bean.User;import com.example.demo1.Mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;@Servicepublic class UserService {        @Autowired        private UserMapper userMapper;        public String selectUserName(User user) {            String userName = user.getUserName();            String userPassword = user.getPassword();            System.out.println(userName);            System.out.println(userPassword);            String result = "-1";            // 将输入的密码使用md5加密            String passwordMD5 = passwordMD5(userName, userPassword);            // 用户不存在            if (userMapper.selectUserName(userName) == null) {                result = "0";                return result;            //  用户存在,但密码输入错误            }else if(!userMapper.selectUserPassword(userName).equals(passwordMD5) ){                result = "1";                return result;            //  登录成功            }else if(userMapper.selectUserPassword(userName).equals(passwordMD5)) {                result = "2";                return result;            }            return result;        }        public String addUser(User user) {            String userName = user.getUserName();            // 用户存在            if(userMapper.selectUserName(userName) != null)                return "0";            String userPassword = user.getPassword();            System.out.println(userName + "***" + userPassword);            String passwordMD5 = passwordMD5(userName, userPassword);            userMapper.addUser(userName, passwordMD5);            return "1";        }        // md5加密        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;        }}

4.5、控制层UserController.java

package com.example.demo1.Controller;import com.example.demo1.Bean.User;import com.example.demo1.Service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/user")public class UserController {    @Autowired    private UserService userService;    @ResponseBody    @RequestMapping(value = "/register",method = RequestMethod.POST)    public String register(@RequestBody User user) {        return userService.addUser(user);    }    @ResponseBody    @RequestMapping(value = "/login", method = RequestMethod.POST)    public String login(@RequestBody User user) {        return userService.selectUserName(user);    }}

5、前端代码

(一)、login.html

<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"><head>    <meta charset="UTF-8">    <title>用户登录title>    <link  href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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>    <form id = "app" >        <img src="img/P.jpeg" 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/login', {                        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 = '/successLogin.html'                    }).catch(function () {                        console.log("传输失败")                    })                },                register:function () {                    window.location.href = "register.html"                }            }        })script>body>html>

(二)、sucessLogin.html

<html lang="en"><head>    <meta charset="UTF-8">    <title>成功登录title>    <link  href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">head><body class="text-center">    <h1 >成功登录h1>body>html>

(三)、register.html

html><html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"><head>    <meta charset="UTF-8">    <title>用户注册title>    <link  href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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>    <form id = "app">        <img src="img/P.jpeg" 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>      <script src="https://unpkg.com/axios/dist/axios.min.js">script>    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>  <script>        var pang = new Vue({            el:"#app",            data:{                userName: '',                userPassword: '',                msg: '',            },            methods:{                //只能输入英文、数字                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/register', {                            userName: this.userName,                            userPassword: this.userPassword,                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域                        }).then(function (dat) {                            if (dat.data == '1') {                                window.location.href = '/successRegister.html'                            }else {                                alert("注册失败, 该用户名已经存在!")                            }                        })                    }                }            }        })script>body>html>

(四)、sucessRegister.html

<html lang="en"><head>    <meta charset="UTF-8">    <title>成功注册title>    <link  href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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 = "/login.html"                }            }        })script>body>html>

6、结果测试:运行Demo1Application.java

(一)、注册页面

以用户名为hachilin,密码为123456注册为例子:

8e6b307188e699ea5891c3b29d66012e.png

(二)、注册成功页面

b5ede847452c8fadadc187bdd8fcb11b.png

(三)、数据库内容

8bbbbbb33e22b1da1df9b38ceb74ddc6.png

(四)、登录页面

cddb0cf0dadf6f27311cd6df673cefb7.png

(五)、登录成功页面

9b567e83edb3bff54404c57146364a74.png

简单小例子,仅供学习参考!

温暖提示

为了方便大家更好的学习,本公众号经常分享项目干货源码案例给大家去练习,如果本公众号没有你要学习的功能案例,你可以联系小编(微信:wcy18898375730)提供你帮助哦!

  • 作者:weixin_39598568
  • 原文链接:https://blog.csdn.net/weixin_39598568/article/details/111170335
    更新时间:2022-06-19 10:29:18