[JavaWeb] 简单的登录注册案例

 ✨✨个人主页:沫洺的主页

📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏 

                           📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏

                           📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏     

💖💖如果文章对你有所帮助请留下三连✨✨

🌈登录注册案例

🎨案例展示

🎨涉及技术

📌JavaWeb---Servlet

📌MyBatis

🎨环境搭建

📌使用IDEA创建maven-web项目,配置pom文件添加坐标依赖及tomcat配置

📌创建目录,包文件夹,在webapp目录下编写静态页面login.html和register.html

📌创建db5数据库,创建 tb_user表,在pojo包下创建 User实体类

📌创建mybatis-config.xml核心配置文件,UserMapper.xml映射文件,UserMapper接口

📌编写LoginServlet和RegisterServlet,及对应的UserMapper映射文件,UserMapper接口

🎨目录展示

🎨环境搭建源码配置

🔎pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.moming</groupId>  
  <artifactId>web-login-register</artifactId>  
  <version>1.0-SNAPSHOT</version>  
  <packaging>war</packaging>
  <properties> 
    <maven.compiler.source>8</maven.compiler.source>  
    <maven.compiler.target>8</maven.compiler.target> 
  </properties>
  <dependencies>
    <!--MyBatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.49</version>
    </dependency>
    <!--分页插件坐标-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>
    <!--servlet运行环境-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!--junit单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
    </dependency>
    <!--JSON-->
    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.8.5</version>
    </dependency>
    <!--日志-->
    <!--添加logback-classic依赖-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!--添加logback-core依赖-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!--实体类注解-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
      <scope>compile</scope>
    </dependency>
    <!--JSP-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
    <!--JSTL-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <!--引入webmvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!--端口号-->
          <port>8080</port>
          <!--虚拟目录-->
          <path>/moming</path>
          <!--解决tomcat7及以前get乱码-->
          <uriEncoding>utf-8</uriEncoding>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

🔎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>
    <!--起别名-->
    <typeAliases>
        <package name="com.moming.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:///db5?useSSL=false&amp;useServerPrepStmts=true&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
        <package name="com.moming.mapper"/>
    </mappers>
</configuration>

 🎨数据库源码

drop table if EXISTS tb_user;
-- 创建用户表
CREATE TABLE tb_user(
	id int primary key auto_increment,
	username varchar(20) unique,
	password varchar(32)
);

-- 添加数据
INSERT INTO tb_user(username,password) values('zhangsan','123'),('lisi','123');

SELECT * FROM tb_user;

🎨静态页面源码

🔎login.css

* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    width: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
    background: url(../imgs/img.png) no-repeat 0px 0px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    -moz-background-size: 100% 100%;
}

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

#loginDiv {
    width: 37%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: rgba(255, 255, 255, 0.27);
    box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
    border-radius: 5px;
}

p {
    margin-top: 30px;
    margin-left: 20px;
}

input {
    margin-left: 15px;
    border-radius: 5px;
    border-style: hidden;
    height: 30px;
    width: 140px;
    outline: none;
    padding-left: 10px;
}
#username{
    width: 200px;
}
#password{
    width: 202px;
}
.button {
    border-color: cornsilk;
    background-color: #5a88c8;
    color: aliceblue;
    border-style: hidden;
    border-radius: 5px;
    width: 100px;
    height: 31px;
    font-size: 16px;
}

#subDiv {
    text-align: center;
    margin-top: 30px;
}
#loginMsg{
    text-align: center;
    color: black;
}

🔎register.css

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

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

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

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

}
.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: 100px;
    margin-left:400px;
    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;
    font-size: 16px;
}
h1{
    text-align: center;
}

🔎img.png

  • 随便替换一个自己的图片就行

🔎login.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link href="css/login.css" rel="stylesheet">
</head>

<body>
<div id="loginDiv">
    <form action="/moming/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="登录">
            <a href="register.html">没有账号?点击注册</a>
        </div>
    </form>
</div>

</body>
</html>

🔎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="login.html">登录</a>
    </div>
    <form id="reg-form" action="/moming/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>

🎨案例源码

🔎UserMapper接口

package com.moming.mapper;

import com.moming.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    //用户登录查询用户
    //@Select("select * from tb_user where username=#{username} and password=#{password}")
    User selectUser(@Param("username") String username, @Param("password") String password);

    //数据库添加用户
    //@Insert("insert into tb_user value(null,#{username},#{password}")
     void insertUser(User user);

     //根据用户名查询用户
    //@Select("select * from tb_user where username=#{username}")
    User selectUserName(@Param("username") String username);
}

🔎User实体类

package com.moming.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}

🔎LoginServlet

package com.moming.web;

import cn.hutool.json.ObjectMapper;
import com.moming.mapper.UserMapper;
import com.moming.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;
import java.util.List;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用MyBatis完成查询
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        //定义配置文件的路径
        String resource = "mybatis-config.xml";
        //资源加载返回字节输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //获取工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3.执行sql
        //参数就是sql语句的唯一标识
        //自动封装结果集
        //3.1使用代理接口,先拿对象,再调方法
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUser(username, password);

        //4.释放资源
        sqlSession.close();
        response.setContentType("text/html;charset=utf-8");
        if(user!=null){
            //存在,登录成功
            response.getWriter().print("登录成功");
        }else {
            //不存在,登录失败
            response.getWriter().print("登录失败");
        }
    }

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

🔎RegisterServlet

package com.moming.web;

import com.moming.mapper.UserMapper;
import com.moming.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  IOException {
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //封装数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //调用mapper根据用户名查询用户对象
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        //定义配置文件的路径
        String resource = "mybatis-config.xml";
        //资源加载返回字节输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //获取工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.执行sql
        //参数就是sql语句的唯一标识
        //自动封装结果集
        //3.1使用代理接口,先拿对象,再调方法
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.selectUserName(username);
        //判断用户对象是否为null
        response.setContentType("text/html;charset=utf-8");
        if(user1==null){
            //用户不存在,可以添加新用户
            mapper.insertUser(user);
            response.getWriter().print("用户创建成功");
            //提交事务
            sqlSession.commit();
            //4.释放资源
            sqlSession.close();
        }else {
            //用户名存在,不能添加
            response.getWriter().print("用户名已存在");
        }
    }

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

🔎UserMapper接口

<?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="com.moming.mapper.UserMapper">
    <!--在<select>标签中,使用resultMap属性替换 resultType属性-->
    <!--<resultMap id="userResultMap" type="User">-->
    <!--    <result column="username" property="username"></result>-->
    <!--    <result column="password" property="password"></result>-->
    <!--</resultMap>-->
    <!--查询数据库是否存在此用户-->
    <select id="selectUser" resultType="User">
        select *
        from tb_user
        where username=#{username} and password=#{password}
    </select>
    <insert id="insertUser" >
        insert into tb_user (id,username,password)
        values (null, #{username},#{password});
    </insert>
    <select id="selectUserName" resultType="User">
        select *
        from tb_user
        where username=#{username};
    </select>

</mapper>

💦 总结说明

此案例比较简单,登录或注册成功及失败后只是在页面同步响应了简单的提示信息,练习的侧重点主要是Servlet、MyBatis的使用,后续会进一步完善其他业务

🧡另外如果需要整个项目源码的在评论区说明🧡

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沫洺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值