【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
相关文章
|
10天前
|
Java 关系型数据库 MySQL
整合SpringBoot与MyBatis时报错时区异常
整合SpringBoot与MyBatis时报错时区异常
14 0
|
13天前
|
存储 关系型数据库 MySQL
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
|
13天前
|
SQL Java 数据库连接
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
|
19天前
|
Java 测试技术 数据库
基于SpringBoot+HTML实现登录注册功能模块
基于SpringBoot+HTML实现登录注册功能模块
|
25天前
|
JavaScript Java 关系型数据库
SpringBoot + Mybatis + Vue的代码生成器
SpringBoot + Mybatis + Vue的代码生成器
32 2
|
28天前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
15 1
|
28天前
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
21 1
|
1月前
|
Java 关系型数据库 MySQL
springboot+mybatis-plus实例demo
springboot+mybatis-plus实例demo
28 0
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
25 0
|
1月前
|
SQL Java 数据库连接
springboot中配置mybatis别名该怎么写?
springboot中配置mybatis别名该怎么写?
22 0

热门文章

最新文章