目录

​ 准备环境及一些登录界面的代码见上一个博客:​

​UserMapper接口添加如下代码:​

​增加注册的静态页面到项目的webapp目录下​

​register.html代码:​

​register.html对应的register.css代码:​

​RegisterServlet代码:​

​执行结果:​

​注册成功示例,数据库就会存入相应的用户名和密码:​

​注册失败示例:​

​代码优化:​

​问题:​

​SqlSessionFactoryUtils工具类代码:​

​将两个文件中的重复代码优化为下面代码:​


流程说明:

1、用户填写用户名,密码等信息,点击注册按钮,提交到Registervlet

2、在Register中使用MyBatis保存数据

3、保存前,需要判断用户名是否已经存在,根据用户名查询数据库

用户注册功能实现及代码优化案例_测试工具

 准备环境及一些登录界面的代码见上一个博客:

UserMapper接口添加如下代码:

    /**
* 根据用户名查询用户对象
* @param username
* @return
*/
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);

/**
* 添加用户
* @param user
*/
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);

增加注册的静态页面到项目的webapp目录下

register.html代码:

<!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="login1.html">登录</a>
</div>
<form id="reg-form" action="/Webapp/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>

register.html对应的register.css代码:

* {
margin: 0;
padding: 0;
list-style-type: none;
}
.reg-content{
padding: 30px;
margin: 3px;
}
a, img {
border: 0;
}

body {
background-image: url("../imgs/reg_bg_min.jpg") ;
text-align: center;
}

table {
border-collapse: collapse;
border-spacing: 0;
}

td, th {
padding: 0;
height: 90px;

}
.inputs{
vertical-align: top;
}

.clear {
clear: both;
}

.clear:before, .clear:after {
content: "";
display: table;
}

.clear:after {
clear: both;
}

.form-div {
background-color: rgba(255, 255, 255, 0.27);
border-radius: 10px;
border: 1px solid #aaa;
width: 424px;
margin-top: 150px;
margin-left:1050px;
padding: 30px 0 20px 0px;
font-size: 16px;
box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
text-align: left;
}

.form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] {
width: 268px;
margin: 10px;
line-height: 20px;
font-size: 16px;
}

.form-div input[type="checkbox"] {
margin: 20px 0 20px 10px;
}

.form-div input[type="button"], .form-div input[type="submit"] {
margin: 10px 20px 0 0;
}

.form-div table {
margin: 0 auto;
text-align: right;
color: rgba(64, 64, 64, 1.00);
}

.form-div table img {
vertical-align: middle;
margin: 0 0 5px 0;
}

.footer {
color: rgba(64, 64, 64, 1.00);
font-size: 12px;
margin-top: 30px;
}

.form-div .buttons {
float: right;
}

input[type="text"], input[type="password"], input[type="email"] {
border-radius: 8px;
box-shadow: inset 0 2px 5px #eee;
padding: 10px;
border: 1px solid #D4D4D4;
color: #333333;
margin-top: 5px;
}

input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
border: 1px solid #50afeb;
outline: none;
}

input[type="button"], input[type="submit"] {
padding: 7px 15px;
background-color: #3c6db0;
text-align: center;
border-radius: 5px;
overflow: hidden;
min-width: 80px;
border: none;
color: #FFF;
box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
}

input[type="button"]:hover, input[type="submit"]:hover {
background-color: #5a88c8;
}

input[type="button"]:active, input[type="submit"]:active {
background-color: #5a88c8;
}
.err_msg{
color: red;
padding-right: 170px;
}
#password_err,#tel_err{
padding-right: 195px;
}

#reg_btn{
margin-right:50px; width: 285px; height: 45px; margin-top:20px;
}

RegisterServlet代码:

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、接收用户密码
String username = request.getParameter("username");
String password = request.getParameter("password");

//封装用户对象
User user = new User();
user.setUsername(username);
user.setPassword(password);

//2、使用mapper,根据用户名查询用户对象
//2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

//2.4使用方法
User u = userMapper.selectByUsername(username);

//3、判断用户对象是否为null
if( u == null){
// 用户名不存在,添加用户
userMapper.add(user);

//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
} else {
//用户名存在,给出提示信息
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("用户名已存在");
}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

执行结果:

用户注册功能实现及代码优化案例_前端_02

 注册成功示例,数据库就会存入相应的用户名和密码:

用户注册功能实现及代码优化案例_java_03

注册失败示例:

用户注册功能实现及代码优化案例_前端_04

代码优化:

创建SqlSessionFactory代码优化下面的重复代码:

//2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

问题:

1、代码重复:使用工具类优化

2、SqlSessionFactory工厂只创建一次,不要重复创建:利于静态代码块特性优化

SqlSessionFactoryUtils工具类代码:

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {

private static SqlSessionFactory sqlSessionFactory;

static {
//静态代码块会随着类的加载而自动执行,且只执行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}

将两个文件中的重复代码优化为下面代码:

SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();     

自此代码优化结束。