【Java实战篇】SpringBoot+MyBatis快速实现登录注册

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 【1月更文挑战第19天】【Java实战篇】SpringBoot+MyBatis快速实现登录注册

 目录

项目结构:

数据库表:

项目依赖:POM文件

Properties配置文件:

静态页面:

Login.html:

Reg.html:

Success.html:

END1.html:

END2.html:

login.css:

背景图片:

MVC架构:

Dao数据库持久层:

Service业务逻辑层:

Controller控制层:


案例展示:

使用SpringBoot+MyBatis完成登录注册板块:

image.gif编辑

项目结构:

image.gif编辑

数据库表:

📎student.sql

-- auto-generated definition
create table student
(
    stu_id       int unsigned zerofill auto_increment comment '学生id'
        primary key,
    stu_name     varchar(40) not null comment '学生姓名',
    stu_no       varchar(50) not null comment '学生学号',
    stu_phone    varchar(50) null comment '学生电话',
    stu_password varchar(50) not null comment '学生密码'
);

image.gif

项目依赖:POM文件

使用了Lombok简化了开发!!!

<?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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.krian</groupId>
    <artifactId>demo</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
<!--            <resources>-->
<!--                <resource>-->
<!--                    <directory>src/main/resources</directory>-->
<!--                    <includes>-->
<!--                        <include>**/*.properties</include>-->
<!--                        <include>**/*.xml</include>-->
<!--                        <include>**/*.html</include>-->
<!--                        <include>**/*.jpg</include>-->
<!--                    </includes>-->
<!--                    <filtering>true</filtering>-->
<!--                </resource>-->
<!--                <resource>-->
<!--                    <directory>src/main/java</directory>-->
<!--                    <includes>-->
<!--                        <include>**/*.properties</include>-->
<!--                        <include>**/*.xml</include>-->
<!--                    </includes>-->
<!--                    <filtering>true</filtering>-->
<!--                </resource>-->
<!--            </resources>-->
    </build>
</project>

image.gif

Properties配置文件:

配置了数据库连接信息

#数据库连接信息:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/milib?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=131452
#配置mapper:
mybatis.mapper-locations=classpath:mapper/*.xml
#关闭Thymeleaf页面缓存:
spring.thymeleaf.cache=false
#开启驼峰命名:
mybatis.configuration.map-underscore-to-camel-case=true

image.gif

静态页面:

Login.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <link rel="stylesheet" th:href="@{/css/login.css}">
    <style>
        #s1{
            float: left;
            margin: 50px 0px 0px 100px;
        }
        #s2{
            float: left;
            margin: 50px 0px 0px 50px;
        }
    </style>
    <script type="text/javascript">
        function f2(){
            var regx = /^[a-zA-Z0-9]{5,12}$/;
            var password = document.getElementById("password").value;
            if(regx.test(password)){
                document.getElementById("d2").style.color = "green";
                document.getElementById("d2").innerHTML="√";
                return true;
            }else{
                document.getElementById("d2").style.color = "red";
                document.getElementById("d2").innerHTML="请重新输入!!!";
                return false;
            }
        }
        function subForm(){
            if (f2()){
                return true;
            }
            return false;
        }
    </script>
</head>
<body>
<div>
    <form th:action="@{/result}" method="get" onsubmit="return subForm()">
        <table>
            <tr>
                <td><span>用户名:</span></td>
                <td><input id="username" type="text" name="username" placeholder="请输入您的用户名" onblur="f1()"><span id="d1"></span></td>
            </tr>
            <tr>
                <td>
                    <span>密码:</span>
                </td>
                <td><input id="password" type="password" name="password" placeholder="请输入您的密码" onblur="f2()"><span id="d2"></span></td>
            </tr>
        </table>
        <input id="s1" type="submit" value="登录">
    </form>
    <form th:action="@{/reg}" method="get" >
        <input id="s2" type="submit" value="注册" onclick="zhuCe()">
    </form>
</div>
</body>
</html>

image.gif

Reg.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <link rel="stylesheet" th:href="@{/css/login.css}">
    <style type="text/css">
        #s1{
            float: left;
            margin: 50px 0px 0px 120px;
        }
    </style>
    <script type="text/javascript">
        function f2(){
            var regx = /^[a-zA-Z0-9]{5,12}$/;
            var password = document.getElementById("password").value;
            if(regx.test(password)){
                document.getElementById("d2").style.color = "green";
                document.getElementById("d2").innerHTML="√";
                return true;
            }else{
                document.getElementById("d2").style.color = "red";
                document.getElementById("d2").innerHTML="×";
                return false;
            }
        }
        function subForm(){
            if (f2()){
                return true;
            }
            return false;
        }
    </script>
</head>
<body>
<form action="/end" method="get" onsubmit="return subForm()">
    <table>
        <tr>
            <td> <span>用户名:</span></td>
            <td><input id="username" type="text" name="username" placeholder="请输入您想要设置的用户名!"><span id="d1"></span></td>
        </tr>
        <tr>
            <td>
                <span>密码:</span>
            </td>
            <td><input id="password" type="password" name="password" placeholder="请输入您想要设置的密码!" onblur="f2()"><span id="d2"></span></td>
        </tr>
        <tr>
            <td>
                <span>学号:</span>
            </td>
            <td><input id="stuNo" type="text" name="stuNo" placeholder="请输入您的学号!"><span id="d3"></span></td>
        </tr>
        <tr>
            <td>
                <span>电话:</span>
            </td>
            <td><input id="phone" type="text" name="phone" placeholder="请输入您的电话号码!"><span id="d4"></span></td>
        </tr>
        <tr>
            <td></td>
            <td><input id="s1" type="submit" value="注册"></td>
        </tr>
    </table>
</form>
</body>
</html>

image.gif

Success.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" th:href="@{/css/login.css}">
  </style>
</head>
<body>
<h1>Hi,欢迎登录!</h1>
</body>
</html>

image.gif

END1.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>注册成功</title>
  <link rel="stylesheet" th:href="@{/css/login.css}">
  <script type="text/javascript">
    window.onload = function f() {
      var i =5;
      var a = setInterval(function () {
        i--;
        if(i<=0){
          document.getElementById("p1").innerHTML = "注册成功,返回登录界面";
          clearInterval(a);
          location = "/tologin";
        }else {
          document.getElementById("p1").innerHTML = "注册成功,还有"+i+"秒跳转回登录界面";
          return false;
        }
      },1000)
    }
  </script>
</head>
<body>
<p id="p1">注册成功,还有5秒跳转回登录界面</p>
</body>
</html>

image.gif

END2.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>注册失败</title>
  <link rel="stylesheet" th:href="@{/css/login.css}">
  <script type="text/javascript">
    window.onload = function f() {
      var i =5;
      var a = setInterval(function () {
        i--;
        if(i<=0){
          document.getElementById("p1").innerHTML = "注册失败,返回登录界面";
          clearInterval(a);
          location = "/tologin";
        }else {
          document.getElementById("p1").innerHTML = "注册失败,还有"+i+"秒跳转回登录界面";
          return false;
        }
      },1000)
    }
  </script>
</head>
<body>
<p id="p1">注册失败,还有5秒跳转回登录界面</p>
</body>
</html>

image.gif

login.css:

body{
    background-image: url("../images/back.jpg");
    background-size: 100%;
}

image.gif

背景图片:

image.gif编辑

MVC架构:

Dao数据库持久层:

持久层,定义操作数据库方法:

StudentController.java:
package com.krian.demo.dao.studentDao;
import com.krian.demo.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
 * @Author: Lunaticer
 * @Create: 2021-07-26 23:23
 * @Tip: Keeping the eyes of the prize !
 * @Description: dao持久层,对应daoMapper.xml操作数据库!
 */
@SuppressWarnings({"all"})
@Mapper
@Repository
public interface StuMapper {
    //通过学生姓名查询:
    public Student selectStuByName(String name);
    //插入学生数据:
    public int insertStudent(Student student);
}

image.gif

以接口的形式进行方法的定义,对应DaoMapper.xml对具体的数据库操作进行实现:

StuMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射dao接口类-->
<mapper namespace="com.krian.demo.dao.studentDao.StuMapper">
    <select id="selectStuByName" resultType="com.krian.demo.pojo.Student" parameterType="String">
        select * from student where stu_name = #{name}
    </select>
    <insert id="insertStudent" parameterType="com.krian.demo.pojo.Student">
        insert into student(stu_name,stu_no,stu_phone,stu_password)
                    values (#{stuName},#{stuNo},#{stuPhone},#{stuPassword})
    </insert>
</mapper>

image.gif

Service业务逻辑层:

通过调用Dao层接口,实习具体复杂的业务逻辑:

StudentService.java:

package com.krian.demo.service.StudentService;
import com.krian.demo.dao.studentDao.StuMapper;
import com.krian.demo.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @Author: Lunaticer
 * @Create: 2021-07-26 23:30
 * @Tip: Keeping the eyes of the prize !
 * @Description: 业务逻辑层,调用dao层接口,实现业务逻辑,返回执行结果给控制层!
 */
@SuppressWarnings({"all"})
@Service
public class StudentService {
    @Autowired
    StuMapper stuMapper;
    /**
     * 学生登录
     *
     * @param student
     * @return
     */
    public boolean login(Student student){
        String loginName = student.getStuName();
        String loginPassWord = student.getStuPassword();
        Student loginStudent = stuMapper.selectStuByName(loginName);
        System.out.println("进行验证!!!");
        if (loginStudent == null){
            return false;
        } else if (loginStudent.getStuPassword().equals(loginPassWord)){
            return true;
        } else{
            return false;
        }
    }
    /**
     * 学生注册
     *
     * @param student
     * @return
     */
    public boolean reg(Student student){
        int i = stuMapper.insertStudent(student);
        if (i > 0){
            return true; //注册成功!
        } else {
            return false; //注册失败!
        }
    }
}

image.gif

Controller控制层:

通过调用业务层执行具体业务,通过业务层返回判断,实现具体的页面跳转,视图控制:

StudentController.java:

package com.krian.demo.controller.studentController;
import com.krian.demo.pojo.Student;
import com.krian.demo.service.StudentService.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @Author: Lunaticer
 * @Create: 2021-07-26 23:38
 * @Tip: Keeping the eyes of the prize !
 * @Description: 控制层,接收请求,控制视图跳转!
 */
@SuppressWarnings({"all"})
@Controller
public class StudentController {
    @Autowired
    StudentService studentService;
    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/tologin")
    public String login(){
        return "Login";
    }
    @GetMapping("/result")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        //前端获取数据:
        String studentName = req.getParameter("username");
        String stduentPassword = req.getParameter("password");
        //创建实例,接收前端数据:
        Student student = new Student();
        student.setStuName(studentName);
        student.setStuPassword(stduentPassword);
        //调用Service层方法:
        boolean login = studentService.login(student);
        //判断Service层返回的结果,进行页面的跳转:
        if (login == true){
            return "Success";
        } else {
            return "Login";
        }
    }
    /**
     * 注册
     *
     * @return
     */
    @GetMapping("/reg")
    public String reg(){
        return "Reg";
    }
    @GetMapping("/end")
    public String end(HttpServletRequest req, HttpServletResponse resp) {
        //获取前端数据;
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String stuNo = req.getParameter("stuNo");
        String phone = req.getParameter("phone");
        //创建实例接收数据:
        Student student = new Student();
        student.setStuPassword(password);
        student.setStuNo(stuNo);
        student.setStuName(username);
        student.setStuPhone(phone);
        System.out.println("插入数据!!!");
        //判断Service层返回的结果,进行页面的跳转:
        boolean flog = studentService.reg(student);
        if (flog){
            return "END1"; //注册成功!
        } else {
            return "END2"; //注册失败!
        }
    }
}

image.gif


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
25天前
|
缓存 前端开发 Java
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
|
24天前
|
Java 测试技术 数据库
基于SpringBoot+HTML实现登录注册功能模块
基于SpringBoot+HTML实现登录注册功能模块
|
3天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
9天前
|
人工智能 前端开发 Java
Java语言开发的AI智慧导诊系统源码springboot+redis 3D互联网智导诊系统源码
智慧导诊解决盲目就诊问题,减轻分诊工作压力。降低挂错号比例,优化就诊流程,有效提高线上线下医疗机构接诊效率。可通过人体画像选择症状部位,了解对应病症信息和推荐就医科室。
151 10
|
9天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
10天前
|
存储 数据可视化 安全
Java全套智慧校园系统源码springboot+elmentui +Quartz可视化校园管理平台系统源码 建设智慧校园的5大关键技术
智慧校园指的是以物联网为基础的智慧化的校园工作、学习和生活一体化环境,这个一体化环境以各种应用服务系统为载体,将教学、科研、管理和校园生活进行充分融合。无处不在的网络学习、融合创新的网络科研、透明高效的校务治理、丰富多彩的校园文化、方便周到的校园生活。简而言之,“要做一个安全、稳定、环保、节能的校园。
37 6
|
24天前
|
JavaScript Java 关系型数据库
基于 java + Springboot + vue +mysql 大学生实习管理系统(含源码)
本文档介绍了基于Springboot的实习管理系统的设计与实现。系统采用B/S架构,旨在解决实习管理中的人工管理问题,提高效率。系统特点包括对用户输入的验证和数据安全性保障。功能涵盖首页、个人中心、班级管理、学生管理、教师管理、实习单位管理、实习作业管理、教师评分管理、单位成绩管理和系统管理等。用户分为管理员、教师和学生,各自有不同的操作权限。
|
29天前
|
Java Maven Spring
SpringBoot运行出现 Lookup method resolution failed; nested exception is java.lang.IllegalStateException
SpringBoot运行出现 Lookup method resolution failed; nested exception is java.lang.IllegalStateException
43 0
|
18天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
26天前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
80 2