JavaWeb:登录注册功能实现

发布时间:2024年01月19日

1、用户登录

1.1、环境准备

创建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.servlet</groupId>  
        <artifactId>javax.servlet-api</artifactId>  
        <version>3.1.0</version>  
        <scope>provided</scope> 
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <!--MyBatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <!--MySQL驱动 可以适应mysql8和mysql5-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
</dependencies> 

配置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>
        <!--在控制台显示SQL语句-->
        <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>login</title>
    <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="重置">&nbsp;&nbsp;&nbsp;
            <a href="register.html">没有账号?点击注册</a>
        </div>
    </form>
</div>

</body>
</html>
1.2、需求分析

image-20240118202324174

流程说明

1、用户在登录页面输入用户名和密码,提交请求给LoginServlet

2、在LoginServlet中接收请求和数据用户名和密码

3、在LoginServlt中通过Mybatis实现调用UserMapper来根据用户名和密码查询数据库表

4、将查询的结果封装到User对象中进行返回

5、在LoginServlet中判断返回的User对象是否为null

6、如果为nul,说明根据用户名和密码没有查询到用户,则登录失败,返回"登录失败"数据给前端

7、如果不为null,则说明用户存在并且密码正确,则登录成功,返回"登录成功"数据给前端

1.3、代码实现

在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);

    }
}

进行登录测试

image-20240118210658907

2、用户注册实现

2.1、环境准备

前端注册页面

<!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>
2.2、需求分析

image-20240118211043524

流程说明

1、用户在注册页面输入用户名和密码,提交请求给RegisterServlet

2、在RegisterServlet中接收请求和数据[用户名和密码]

3、在RegisterServlet中通过Mybatis实现调用UserMapper来根据用户名查询数据库表

4、将查询的结果封装到User对象中进行返回

5、在RegisterServlet中判断返回的User对象是否为null

6、如果为nul,说明根据用户名可用,则调用UserMapper来实现添加用户

7、如果不为null,则说明用户不可以,返回"用户名已存在"数据给前端

2.3、代码实现

编写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);
    }
}
文章来源:https://blog.csdn.net/weixin_53961667/article/details/135688707
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。