Mybatis-实现简单登录验证、表格信息展示
一、代码结构
仅仅针对作者本人的提醒:先看五 功能一致性说明:
前端 | HTML | JSP |
---|---|---|
login.html | login.jsp |
.jsp | JDBC | Mybatis |
---|---|---|
main.jsp | main.mybatis.jsp |
.java | JDBC | Mybatis |
---|---|---|
Main_JDBC.java | Main_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
- Referenced Libraries
-
Mybatis需要
- Referenced Libraries
- mysql-connector-java-8.0.18.jar
- mybatis-3.5.6.jar
- Referenced Libraries
三、代码内容
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
- edu/ahau/
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
- edu/ahau/
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
- edu/ahau/
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
- edu/ahau/
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
- edu/ahau/
<?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&characterEncoding=utf8&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