Mybatis&JDBC-实现简单登录验证、表格信息展示

一、代码结构

仅仅针对作者本人的提醒:先看五 在这里插入图片描述功能一致性说明:

前端HTMLJSP
login.htmllogin.jsp
.jspJDBCMybatis
main.jspmain.mybatis.jsp
.javaJDBCMybatis
Main_JDBC.javaMain_Mybatis.java
外部jar包mysql-connector-java-8.0.18.jar前者+mybatis-3.5.6.jar

二、外部包

导入方式请在这里找

  • JDBC需要

    • Referenced Libraries
      • mysql-connector-java-8.0.18.jar
  • Mybatis需要

    • Referenced Libraries
      • mysql-connector-java-8.0.18.jar
      • mybatis-3.5.6.jar

三、代码内容

1.login.html

  • src/main/webapp/
    • login.html
<!DOCTYPE html>
<html lang="zh">
<meta charset="utf-8">
<head>
    <title>main</title>
</head>
<style>
    form * {
        margin: 0.2em;
    }

    label {
        display: flex;
    }

    label > span {
        flex-grow: 1;
    }

    button {
        flex-grow: 1;
        padding: 0.3em;
    }
</style>
<body>
<div style="height:100vh; display: flex; justify-content: center; align-items: center">
    <form action="main.jsp" method="post" style="display: flex; flex-direction: column">
        <label>
            <span>用户名</span>
            <input name="name" type="text"/>
        </label>
        <label>
            <span>密码</span>
            <input name="password" type="password"/>
        </label>
        <div style="display: flex">
            <button type="submit">提交</button>
            <button type="reset">重置</button>
        </div>
    </form>
</div>
</body>
</html>

2.login.jsp

  • src/main/webapp/
    • login.jsp
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<meta charset="utf-8">
<head>
    <title>main</title>
</head>
<style>
    form * {
        margin: 0.2em;
    }

    label {
        display: flex;
    }

    label > span {
        flex-grow: 1;
    }

    button {
        flex-grow: 1;
        padding: 0.3em;
    }
</style>
<body>
<div style="height:100vh; display: flex; justify-content: center; align-items: center">
    <form action="main.jsp" method="post" style="display: flex; flex-direction: column">
        <label>
            <span>用户名</span>
            <input type="text" name="name"/>
        </label>
        <label>
            <span>密码</span>
            <input type="password" name="password"/>
        </label>
        <div style="display: flex">
            <button type="submit">提交</button>
            <button type="reset">重置</button>
        </div>
    </form>
</div>
</body>
</html>

3.main.jsp

  • src/main/webapp/
    • main.jsp
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="jakarta.servlet.http.HttpServletResponse"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<meta charset="utf-8">
<head>
    <title>main</title>
</head>
<style>
    thead, tfoot {
        background-color: #333;
        color: #fff;
    }

    tr {
        line-height: 2em;
    }

    td {
        border: 2px solid #d4d4d4;
        padding: 0.3em;
    }
</style>
<body>
<div style="height:100vh; display: flex; justify-content: center; align-items: center">
    <table style="margin: 10vw; flex-grow: 1; border-collapse: collapse">
        <thead>
        <tr>
            <th>Student ID</th>
            <th>Name</th>
            <th>Password</th>
        </tr>
        </thead>
        <tbody>
        <%request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection connection = DriverManager.getConnection(
                        "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
                        "root", "123456"
                );
                if (connection == null) {
                    throw new Exception("Database connection failed");
                }
                System.out.println("Database connection successful");

                // 获取表单中的参数
                String name = request.getParameter("name");
                String password = request.getParameter("password");
                System.out.printf("Name: %s\tPassword: %s\n", name, password);
                PreparedStatement prepareStatement = connection.prepareStatement(
                        "select exists(select * from student where name = ? and password = ?)"
                );
                // 为SQL中的?设置值
                prepareStatement.setString(1, name);
                prepareStatement.setString(2, password);
                ResultSet results = prepareStatement.executeQuery();
                results.next();
                if (!results.getBoolean(1)) {
                    // 无记录(用户名与密码不正确)
                    results.close();
                    prepareStatement.close();
                    connection.close();
                    // out.println("用户名或密码错误");
                    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); // 状态码 302 (重定向)
                    response.setHeader("Location", "login.jsp"); // 跳转到 login.jsp
                    return;
                }
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery("select * from student");
                while (resultSet.next()) {
                    out.println(String.format(
                            "<tr><td>%s</td><td>%s</td><td>%s</td></tr>",
                            resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)
                    ));
                }
                resultSet.close();
                statement.close();
                connection.close();
            } catch (Exception exception) {
                exception.printStackTrace();
            }%>
        </tbody>
    </table>
</div>
</body>
</html>

4.main.mybatis.jsp

  • src/main/webapp/
    • main.mybatis.jsp
<%@ page import="org.apache.ibatis.session.SqlSession"%>
<%@ page import="edu.ahau.MyBatisSession"%>
<%@ page import="edu.ahau.StudentMapper"%>
<%@ page import="edu.ahau.Student"%>
<%@ page import="jakarta.servlet.http.HttpServletResponse"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<meta charset="utf-8">
<head>
    <title>main</title>
</head>
<style>
    thead, tfoot {
        background-color: #333;
        color: #fff;
    }

    tr {
        line-height: 2em;
    }

    td {
        border: 2px solid #d4d4d4;
        padding: 0.3em;
    }
</style>
<body>
<div style="height:100vh; display: flex; justify-content: center; align-items: center">
    <table style="margin: 10vw; flex-grow: 1; border-collapse: collapse">
        <thead>
        <tr>
            <th>Student ID</th>
            <th>Name</th>
            <th>Password</th>
        </tr>
        </thead>
        <tbody>
        <%request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            try {
                // 获取表单中的参数
                String name = request.getParameter("name");
                String password = request.getParameter("password");
                System.out.printf("Name: %s\tPassword: %s\n", name, password);
                SqlSession sqlSession = MyBatisSession.getSqlSession();
                StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
                boolean hasStudent = studentMapper.selectExists(name, password);
                if (!hasStudent) {
                    // 无记录(用户名与密码不正确)
                    // out.println("用户名或密码错误");
                    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); // 状态码 302 (重定向)
                    response.setHeader("Location", "login.jsp"); // 跳转到 login.jsp
                    return;
                }
                Student[] students = studentMapper.selectAll();
                for (Student student : students) {
                    out.println(String.format(
                            "<tr><td>%s</td><td>%s</td><td>%s</td></tr>",
                            student.getStudentID(), student.getName(), student.getPassword())
                    );
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }%>
        </tbody>
    </table>
</div>
</body>
</html>

5.Main_JDBC.java

  • src/main/java/
    • edu/ahau/
      • Main_JDBC.java
package edu.ahau;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

@WebServlet("/main")
public class Main_JDBC extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
                    "root", "123456"
            );
            if (connection == null) {
                throw new Exception("Database connection failed");
            }
            System.out.println("Database connection successful");

            // 获取表单中的参数
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            System.out.printf("Name: %s\tPassword: %s\n", name, password);
            PreparedStatement prepareStatement = connection.prepareStatement(
                    "select exists(select * from student where name = ? and password = ?)"
            );
            // 为SQL中的?设置值
            prepareStatement.setString(1, name);
            prepareStatement.setString(2, password);
            ResultSet results = prepareStatement.executeQuery();
            results.next();
            if (!results.getBoolean(1)) {
                // 无记录(用户名与密码不正确)
                results.close();
                prepareStatement.close();
                connection.close();
                // response.getWriter().println("用户名或密码错误");
                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); // 状态码 302 (重定向)
                response.setHeader("Location", "login.jsp"); // 跳转到 login.jsp
                return;
            }
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from student");
            while (resultSet.next()) {
                response.getWriter().printf(
                        "Student ID:%s\tName: %s\tPassword: %s\n",
                        resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)
                );
            }
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

6.Main_MyBatis.java

  • src/main/java/
    • edu/ahau/
      • Main_MyBatis.java
package edu.ahau;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

@WebServlet("/main")
public class Main_MyBatis extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            // 获取表单中的参数
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            System.out.printf("Name: %s\tPassword: %s\n", name, password);
            SqlSession sqlSession = MyBatisSession.getSqlSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean hasStudent = studentMapper.selectExists(name, password);
            if (!hasStudent) {
                // 无记录(用户名与密码不正确)
                // response.getWriter().println("用户名或密码错误");
                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); // 状态码 302 (重定向)
                response.setHeader("Location", "login.jsp"); // 跳转到 login.jsp
                return;
            }
            Student[] students = studentMapper.selectAll();
            for (Student student : students) {
                response.getWriter().printf(
                        "Student ID:%s\tName: %s\tPassword: %s\n",
                        student.getStudentID(), student.getName(), student.getPassword()
                );
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

以下为Mybatis配置

7.Student.java

  • src/main/java/
    • edu/ahau/
      • Student.java
package edu.ahau;

public class Student {
    private String studentID;
    private String name;
    private String password;

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

8.StudentMapper.java

  • src/main/java/
    • edu/ahau/
      • StudentMapper.java
package edu.ahau;

import org.apache.ibatis.annotations.Param;

public interface StudentMapper {
    boolean selectExists(@Param("name") String name, @Param("password") String password);

    Student[] selectAll();
}

9.StudentMapper.xml

  • src/main/java/
    • edu/ahau/
      • StudentMapper.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">
<mapper namespace="edu.ahau.StudentMapper">
    <select id="selectExists" resultType="boolean">
        select exists(select * FROM student where name = #{name} and password = #{password})
    </select>

    <select id="selectAll" resultType="edu.ahau.Student">
        select *
        FROM student
    </select>
</mapper>

10.MyBatis_Config.xml

  • src/main/resources/
    • MyBatis_Config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--当返回行的所有列都是空时,MyBatis默认返回null-->
        <setting name="returnInstanceForEmptyRow" value="true"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="edu/ahau/StudentMapper.xml"/>
    </mappers>
</configuration>

四、数据库文件

三个字段

-- test.student definition

CREATE TABLE `student` (
    `student_id` varchar(10) NOT NULL,
    `name` varchar(100) NOT NULL,
    `password` varchar(100) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

五、请忽略

README.txt

创建 Dynamic Web Project
复制 src 文件夹
配置 Eclipse:
    导入 jar 包:
        Build Path
        Configure Build Path...
        Libraries
        Add External JARS...
    添加 jar 包:
        Run
        Run Configurations...
        Classpath
        User Entries
        Add External JARS...
选择 Servlet 或 JSP
选择 JDBC 或 MyBatis
更改名称:
    Main_JDBC
    Main_MyBatis
    Student
    StudentMapper
    StudentMapper.xml
    login.html
    login.jsp
    main.jsp
    main.mybatis.jsp
更改数据库字段:
    Main_JDBC
    Main_MyBatis
    Student
    StudentMapper
    StudentMapper.xml
    main.jsp
    main.mybatis.jsp
更改/删除网页中的 style
删除注释
删除多余的文件, 包括:
    .idea
    out
    build
    table.sql
    README.txt
    Web.iml
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
mybatis-spring-boot-starter 和 spring-boot-starter-jdbc 是用于在 Spring Boot 项目中连接数据库的两个依赖包。它们有不同的功能和用途。 mybatis-spring-boot-starter 是 MyBatis 官方提供的一个 Spring Boot Starter,它包含了使用 MyBatis 进行数据库访问所需的所有依赖。通过引入 mybatis-spring-boot-starter,您可以方便地使用 MyBatis 进行数据库操作,而无需单独引入 spring-boot-starter-jdbc 。 spring-boot-starter-jdbc 是 Spring Boot 官方提供的一个 Starter,用于支持使用 JDBC 进行数据库访问。如果您不使用 MyBatis,而只是使用 Spring 的 JdbcTemplate 进行数据库操作,那么您需要引入 spring-boot-starter-jdbc 依赖。它提供了一些必要的配置和支持,使您可以方便地使用 JDBC 进行数据库访问 。 引用的内容中提到,如果您已经引入了 mybatis-spring-boot-starter,那么您不再需要单独引入 spring-boot-starter-jdbc。这是因为 mybatis-spring-boot-starter 已经包含了 spring-boot-starter-jdbc 的依赖。这样,您就可以直接使用 MyBatis 进行数据库操作,而无需关注底层的 JDBC 配置 。 总结起来,mybatis-spring-boot-starter 是用于集成 MyBatis 的 Spring Boot Starter,而 spring-boot-starter-jdbc 是用于支持使用 JDBC 进行数据库操作的 Spring Boot Starter。如果您使用 MyBatis,建议直接引入 mybatis-spring-boot-starter,它已经包含了必要的 JDBC 依赖。如果您只是使用 Spring 的 JdbcTemplate,那么需要引入 spring-boot-starter-jdbc 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值