20220714_Servlet_综合案例_登录和注册

Tomcat服务器开启多次容易出现8080端口已被绑定的报错
这时打开cmd输入
netstat -o -n -a | findstr :8080
查看占用8080的端口进程,输入
taskkill /F /PID 进程号
干掉之后,再开tomcat就可

本例完整项目结构
请添加图片描述

文章目录


一,不管三七二十一先准备数据库

show databases ;

show tables ;

drop database if exists User7;
create database user7;
use user7;
drop table if exists users;
create table users
(
    id       int primary key auto_increment,
    username varchar(20) unicode,
    password varchar(32)
);

insert into users(username, password)
values ('leon', '1234'),
       ('ashley', '2345'),
       ('ada', '3456'),
       ('louis', '4567');

select *
from users;

请添加图片描述

文章目录


二,配置文件部分
1.整个maven项目的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>org.example</groupId>
    <artifactId>Web_Login_Reg_Case</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
    </dependencies>

    <!--tomcat plugin-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!--<configuration>
                    <path>/Web_Login_Reg_Case</path>
                </configuration>-->
            </plugin>
        </plugins>
    </build>

</project>

2.mybatis核心配置文件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.diy.pojo"/>
    </typeAliases>

    <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:///user7?useSSl=false&amp;useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--此处加载sql的映射文件-->
        <package name="com.diy.mapper"/>
    </mappers>
</configuration>

2.映射文件UserMapper.xml,命名空间指向的就是同名接口

<?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.diy.mapper.UserMapper">

</mapper>

3.映射文件命名空间指向同名路径下的同名接口类UserMapper,接口代码如下

package com.diy.mapper;

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

public interface UserMapper {
    /**
     * If we don't user annotation here, write the sql statement will at UserMapper.xml
     * this method for login check, whether the user is exists or not
     * @param username
     * @param password
     * @return
     */
    @Select("select * from user7.users where username = #{username} and password = #{password}")
    User select(@Param("username")String username, @Param("password")String password);

}

文章目录


二,访问部分
资源之一,登录页面html

<!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="/Web_Login_Reg_Case/loginServlet" method="post" id="form">
        <h1 id="loginMsg">LOGIN IN</h1>
        <p>Username:<input id="username" name="username" type="text"></p>

        <p>Password:<input id="password" name="password" type="password"></p>

        <div id="subDiv">
            <input type="submit" class="button" value="login up">
            <input type="reset" class="button" value="reset">&nbsp;&nbsp;&nbsp;
            <a href="register.html">Not a member? Click for Registry</a>
        </div>
    </form>
</div>

</body>
</html>

登录页的CSS

* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    width: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
    background: url(../imgs/Desert.jpg) 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(75, 81, 95, 0.3);
    box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
    border-radius: 5px;
}

#name_trip {
    margin-left: 50px;
    color: red;
}

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

input {
    margin-left: 15px;
    border-radius: 5px;
    border-style: hidden;
    height: 30px;
    width: 140px;
    background-color: rgba(216, 191, 216, 0.5);
    outline: none;
    color: #f0edf3;
    padding-left: 10px;
}
#username{
    width: 200px;
}
#password{
    width: 202px;
}
.button {
    border-color: cornsilk;
    background-color: rgba(100, 149, 237, .7);
    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: aliceblue;
}

处理登录的LoginServlet的java代码

package com.diy.web;

import com.diy.mapper.UserMapper;
import com.diy.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.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.first get user's name and pw through req object
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.1 use mybatis, first get an object SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream ins = Resources.getResourceAsStream(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(ins);

        //2.2 get SqlSession object
        SqlSession SqlSess = ssf.openSession();

        //2.3 get mapper
        UserMapper mapper = SqlSess.getMapper(UserMapper.class);

        //2.4 invoke method
        User rs = mapper.select(username, password);

        //2.5 close resource
        SqlSess.close();

        /**
         * 3. now we already have the rs, it is a user object,
         * judge whether it is null, we know login succeed or failed
         * first we need a char output stream
         */
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter wr = resp.getWriter();
        if (rs != null) {
            wr.write("Login Succeed~~~");
        }else {
            wr.write("Sorry, seems you are not a member yet~~~");
        }


    }

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

登录页面图,登录成功和失败的响应图就不贴了,背景图自行准备两张壁纸即可
请添加图片描述

文章目录


注册页面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>Welcome</h1>
        <span>Already a member?</span> <a href="login.html">Login</a>
    </div>
    <form id="reg-form" action="/Web_Login_Reg_Case/registerServlet" method="post">

        <table>

            <tr>
                <td>Username</td>
                <td class="inputs">
                    <input name="username" type="text" id="username">
                    <br>
                    <span id="username_err" class="err_msg" style="display: none">That name can't use</span>
                </td>

            </tr>

            <tr>
                <td>Password</td>
                <td class="inputs">
                    <input name="password" type="password" id="password">
                    <br>
                    <span id="password_err" class="err_msg" style="display: none">Wrong Password Format</span>
                </td>
            </tr>

        </table>

        <div class="buttons">
            <input value="Registry" type="submit" id="reg_btn">
        </div>
        <br class="clear">
    </form>

</div>
</body>
</html>

注册页面的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的代码

package com.diy.web;

import com.diy.mapper.UserMapper;
import com.diy.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.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. get username and password inputting
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2. put inputting in a User object
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //3.connect to database
        String resource = "mybatis-config.xml";
        InputStream ins = Resources.getResourceAsStream(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(ins);

        SqlSession SqlSess = ssf.openSession();

        UserMapper mapper = SqlSess.getMapper(UserMapper.class);

        //4.invoke method
        User us = mapper.selByUname(username);

        //if judge
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter wr = resp.getWriter();

        if (us == null) {
            mapper.newJoin(user);
            wr.write("Registry succeed");

            SqlSess.commit();

            SqlSess.close();

        }else {
            wr.write("Sorry, this name already exist");
        }
    }

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

注册页面效果图,注册成功和失败的响应图不贴了,背景图自行准备
请添加图片描述

注册成功后查看数据库,我注册了两个新的
数据库查看表结果图
请添加图片描述

文章目录


本例的代码优化
将创建sql会话工厂的重复代码,做成工具类,当一个servlet调用一次,该类会加载进内存,并生成一个sql工厂,这个工厂一直在内存里,当另一个servlet调用时,就会以同一个工厂提供服务

package com.diy.util;

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 SqlSessFacUtils {

    private static SqlSessionFactory ssf;

    static {

        try {
            String resource = "mybatis-config.xml";
            InputStream ins = Resources.getResourceAsStream(resource);
            ssf = new SqlSessionFactoryBuilder().build(ins);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

用上自创工具类之后的LoginServlet

package com.diy.web;

import com.diy.mapper.UserMapper;
import com.diy.pojo.User;
import com.diy.util.SqlSessFacUtils;
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.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.first get user's name and pw through req object
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.1 use mybatis, first get an object SqlSessionFactory
//        String resource = "mybatis-config.xml";
//        InputStream ins = Resources.getResourceAsStream(resource);
//        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(ins);
        /**
         * use this way get a ssf, when it loaded into memory, it always exists at there
         * and can serve for others invoking
         */
        SqlSessionFactory ssf = SqlSessFacUtils.getSqlSessionFactory();

        //2.2 get SqlSession object
        SqlSession SqlSess = ssf.openSession();

        //2.3 get mapper
        UserMapper mapper = SqlSess.getMapper(UserMapper.class);

        //2.4 invoke method
        User rs = mapper.select(username, password);

        //2.5 close resource
        SqlSess.close();

        /**
         * 3. now we already have the rs, it is a user object,
         * judge whether it is null, we know login succeed or failed
         * first we need a char output stream
         */
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter wr = resp.getWriter();
        if (rs != null) {
            wr.write("Login Succeed~~~");
        }else {
            wr.write("Sorry, seems you are not a member yet~~~");
        }
        
    }

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

用上自创工具类之后的RegisterServlet

package com.diy.web;

import com.diy.mapper.UserMapper;
import com.diy.pojo.User;
import com.diy.util.SqlSessFacUtils;
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.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. get username and password inputting
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2. put inputting in a User object
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //3.connect to database
//        String resource = "mybatis-config.xml";
//        InputStream ins = Resources.getResourceAsStream(resource);
//        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(ins);
        /**
         * use this way get a ssf, when it loaded into memory, it always exists at there
         * and can serve for others invoking
         */
        SqlSessionFactory ssf = SqlSessFacUtils.getSqlSessionFactory();

        SqlSession SqlSess = ssf.openSession();

        UserMapper mapper = SqlSess.getMapper(UserMapper.class);

        //4.invoke method
        User us = mapper.selByUname(username);

        //if judge
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter wr = resp.getWriter();

        if (us == null) {
            mapper.newJoin(user);
            wr.write("Registry succeed");

            SqlSess.commit();

            SqlSess.close();

        }else {
            wr.write("Sorry, this name already exist");
        }
    }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值