创建SQL
-- 创建数据库
CREATE DATABASE request_test;
USE request_test;
-- 创建用户表
CREATE TABLE tb_user(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) UNIQUE,
`password` VARCHAR(32)
)DEFAULT CHARSET=utf8;
-- 添加数据
INSERT INTO tb_user(username,`password`) VALUES('zhangsan','123'),('lisi','234');
SELECT * FROM tb_user;
新建web项目并在pom.xml添加依赖
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.46version>
dependency>
dependencies>
配置mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<typeAliases>
<package name="com.demo.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/request_test?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.demo.mapper"/>
mappers>
configuration>
创建POJO类
public class User {
private Integer id;
private String username;
private String password;
...省略get和set方法
}
在com.demo.mapper包下创建UserMapper接口
public interface UserMapper {
}
创建工具类
// 这是MyBatis的工具类,简化MyBatis代码
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
// 我们只需要一个SqlSessionFactory,在静态代码块中创建SqlSessionFactory
static {
try {
// 编写代码让MyBatis跑起来,执行SQL语句
String resource = "mybatis-config.xml";
// 加载核心配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 得到SqlSession工厂,赋值给成员变量
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 返回SqlSessionFactory
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
// 返回SqlSession
public static SqlSession openSqlSession() {
return sqlSessionFactory.openSession();
}
public static SqlSession openSqlSession(boolean autoCommit) {
return sqlSessionFactory.openSession(autoCommit);
}
}
前端登录页面
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
<link href="css/login.css" rel="stylesheet">
head>
<body>
<div id="loginDiv">
<form action="loginServlet" method="post" id="form">
<h1 id="loginMsg">登录h1>
<p>用户名:<input id="username" name="username" type="text">p>
<p>密码:<input id="password" name="password" type="password">p>
<div id="subDiv">
<input type="submit" class="button" value="登录">
<input type="reset" class="button" value="重置">
<a href="register.html">没有账号?点击注册a>
div>
form>
div>
body>
html>
流程说明
1、用户在登录页面输入用户名和密码,提交请求给LoginServlet
2、在LoginServlet中接收请求和数据用户名和密码
3、在LoginServlt中通过Mybatis实现调用UserMapper来根据用户名和密码查询数据库表
4、将查询的结果封装到User对象中进行返回
5、在LoginServlet中判断返回的User对象是否为null
6、如果为nul,说明根据用户名和密码没有查询到用户,则登录失败,返回"登录失败"数据给前端
7、如果不为null,则说明用户存在并且密码正确,则登录成功,返回"登录成功"数据给前端
在UserMapper接口中提供一个根据用户名和密码查询用户对象的方法
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
创建LoginServlet.java
1、接受用户账号密码
2、使用UserMapper进行数据查询,返回User对象
3、判断User对象是否为null
为null:登录失败
不为null:登录成功
@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决POST中文乱码问题
request.setCharacterEncoding("UTF-8");
//解决输入流中文乱码问题
response.setContentType("text/html;charset=utf-8");
// 接收用户名密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 用户查询
SqlSession sqlSession = MyBatisUtils.openSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.select(username, password);
if (user != null){
response.getWriter().write(username + "登录成功");
} else {
response.getWriter().write(username + "登录失败");
}
sqlSession.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
进行登录测试
前端注册页面
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册title>
<link href="css/register.css" rel="stylesheet">
head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册h1>
<span>已有帐号?span> <a href="login.html">登录a>
div>
<form id="reg-form" action="registerServlet" method="post">
<table>
<tr>
<td>用户名td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎span>
td>
tr>
<tr>
<td>密码td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误span>
td>
tr>
table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
div>
<br class="clear">
form>
div>
body>
html>
流程说明
1、用户在注册页面输入用户名和密码,提交请求给RegisterServlet
2、在RegisterServlet中接收请求和数据[用户名和密码]
3、在RegisterServlet中通过Mybatis实现调用UserMapper来根据用户名查询数据库表
4、将查询的结果封装到User对象中进行返回
5、在RegisterServlet中判断返回的User对象是否为null
6、如果为nul,说明根据用户名可用,则调用UserMapper来实现添加用户
7、如果不为null,则说明用户不可以,返回"用户名已存在"数据给前端
编写UserMapper提供根据用户名查询用户数据方法和添加用户方法
public interface UserMapper {
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
@Insert("insert into request_test.tb_user values (null,#{username},#{password})")
void insertUser(@Param("username") String username,@Param("password") String password);
@Select("select * from tb_user where username = #{username}")
User selectByUsername(@Param("username") String username);
}
创建RegisterServlet类
@WebServlet(value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决POST中文乱码问题
request.setCharacterEncoding("UTF-8");
//解决输入流中文乱码问题
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+" "+password);
SqlSession sqlSession = MyBatisUtils.openSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectByUsername(username);
if (user == null){
mapper.insertUser(username, password);
sqlSession.commit();
response.getWriter().write("注册成功");
} else {
response.getWriter().write("用户名已经存在");
}
sqlSession.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request,response);
}
}