Use Servlet + Mysql to implement simple login and registration functions and layering between projects based on Java Web

1. Layering of code

1 Overview

        A good hierarchical division can not only make the code structure clearer, but also make the project division of labor clearer, greatly improve the readability, and follow it home to facilitate later maintenance and upgrades. From another perspective, a good code layering architecture should be able to match the single responsibility principle well. In this way, the dependence between layers can be reduced, and the logic of each layer can be reused to the maximum extent possible.

2. Benefits of layering

  • High cohesion: The layered design can simplify the system design and allow different layers to focus on doing a certain module.
  • Low coupling: layers interact through interfaces or APIs, and the relying party does not need to know the details of the dependent party
  • Reuse: After layering, a high level of reuse can be achieved
  • Scalability: The layered architecture makes it easier for us to scale horizontally

 If the system is not layered, when the business scale increases or the traffic increases, we can only expand the overall system. After layering, it is easy to extract some modules and form an independent system.

3. Construction package

We need to build three packages: bean, dao, util

        The dao layer (data access layer) here accesses data with the database, the service is the business logic layer, which interacts with the data access layer, and the controller is the control layer that processes and responds to front-end requests. .
       The bean package (entity class) contains entity classes, which makes it more convenient to operate data.

        The uitl package (toolkit) encapsulates frequently used methods.

2. Preparation of home page

Create an index.jsp project under the web project to write the homepage

The location of index.jsp is as shown below:

 

I set two hyperlinks on the homepage to jump to the page, pointing to the login page and registration page respectively.

As shown below:

 The implementation code is as follows:

<html>
  <head>
    <title>Java Web</title>
  </head>
  <body>
    <a href="Login.jsp"><h2>去登录</h2></a>
    <a href="Enroll.jsp"><h2>去注册</h2></a>
  </body>
</html>

3. Writing the front-end login page

In the login page we need to useJDBC to connect to the database to perform data query operations (to determine whether the account and password entered by the user are correct) a>

First, we build a Login.jsp project under the web project to write the login page.

The location of Login.jsp is as shown below:

 Display of the login page:

 The code to implement the login page is as follows:

<html>
<head>
    <title>登录</title>
</head>
<style type="text/css">
    .login-card {
        width: 300px;
        margin: 0 auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 10px;
        background-color: #e8e8e8;
        box-shadow: 2px 2px 10px #ccc;
    }

    .card-header {
        text-align: center;
        margin-bottom: 20px
    }

    .card-header .log {
        margin: 0;
        font-size: 24px;
        color: black;
    }

    .form-group {
        margin-bottom: 15px;
    }

    label {
        font-size: 18px;
        margin-bottom: 5px;
    }

    input[type="text"], input[type="password"] {
        width: 100%;
        padding: 12px 20px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
        transition: 0.5s;
    }

    input[type="submit"] {
        width: 100%;
        background-color: #333;
        color: white;
        padding: 14px 20px;
        margin: 8px 0;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    input[type="submit"]:hover {
        background-color: #ccc;
        color: black;
    }

</style>
<body>
<div class="login-card">
    <div class="card-header">
        <div class="log">登录</div>
    </div>
    <form action="login" method="post">
        <div class="form-group">
            <label for="user">账号:</label>
            <input required="" name="user" id="user" type="text">
        </div>
        <div class="form-group">
            <label for="pwd">密码:</label>
            <input required="" name="pwd" id="pwd" type="password">
        </div>
        <div class="form-group">
            <input value="登录" type="submit">&nbsp;&nbsp;&nbsp;
            <a href="Enroll.jsp">没有账号?去注册</a>
        </div>
    </form>
</div>

</body>
</html>

4. Preparation of front-end registration page

In the registration page, we need to use JDBC to connect to the database to add data (obtain the data in the request sent by the browser through servlet and add it to the database)

Before adding data, we first build an Enroll.jsp project under the web project

The location of Enroll.jsp is as shown below:

 Display of registration page:

 The code to implement the registration page is as follows:

<html>
<head>
    <title>注册账号</title>
</head>
<style type="text/css">
    .login-card {
        width: 300px;
        margin: 0 auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 10px;
        background-color: #e8e8e8;
        box-shadow: 2px 2px 10px #ccc;
    }

    .card-header {
        text-align: center;
        margin-bottom: 20px
    }

    .card-header .log {
        margin: 0;
        font-size: 24px;
        color: black;
    }

    .form-group {
        margin-bottom: 15px;
    }

    label {
        font-size: 18px;
        margin-bottom: 5px;
    }

    input[type="text"], input[type="password"] {
        width: 100%;
        padding: 12px 20px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
        transition: 0.5s;
    }

    input[type="submit"] {
        width: 100%;
        background-color: #333;
        color: white;
        padding: 14px 20px;
        margin: 8px 0;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    input[type="submit"]:hover {
        background-color: #ccc;
        color: black;
    }

</style>
<body>
<div class="login-card">
    <div class="card-header">
        <div class="log">注册</div>
    </div>
    <form action="enroll" method="post">
        <div class="form-group">
            <label for="zhangh">添加账号:</label>
            <input required="" name="zhangh" id="zhangh" type="text">
        </div>
        <div class="form-group">
            <label for="pwd">设置密码:</label>
            <input required="" name="pwd" id="pwd" type="password">
        </div>
        <div class="form-group">
            <label for="dell">添加电话:</label>
            <input required="" name="dell" id="dell" type="text">
        </div>
        <div class="form-group">
            <label for="address">添加地址:</label>
            <input required="" name="address" id="address" type="text">
        </div>
        <div class="form-group">
            <input value="注册" type="submit">&nbsp;&nbsp;&nbsp;
            <a href="Login.jsp">已有账号?去注册</a>
        </div>
    </form>
</div>

</body>
</html>

5. Preparation of successful login home page

First we build a ShouYe.jsp under the web project

The location of ShouYe.jsp is as shown below:

 

Display of successful login home page:

The implementation code is as follows:

<html>
<head>
  <meta charset="utf-8">
  <title>首页</title>
  <style type="text/css">
    div{
      position: relative;
      width: 360px;
      height: 511px;
    }
    img{
      border-radius: 5px; /* 设置圆角 */
    }
    p{
      width: 500px;
      height: 300px;
      position: absolute;/* 绝对定位 */
      left: 0;
      top: 0;
      background-color: rgba(0 ,0 ,0 , 0.709);
      color: white;
      padding: 10px;
      display: none;/* 隐藏 */
      pointer-events: none; /* 不对鼠标事件做出反应
			}
		</style>
</head>
<body>
<div id="div_1">
  <img src="img/mhl.jpg" alt="">
  <p>
    <strong>简介</strong>
    <span>
					在钱塘开茶铺的赵盼儿惊闻未婚夫、新科谈话欧阳旭要另娶当朝高官之女,不甘命运的她誓要上京讨个公道。在途中她遇到了出自
					权门但生性正直的皇城司指挥顾千帆,并卷入江南一场大案,两人不打不相识从而结缘。赵盼儿凭借智慧解救了被骗婚而惨遭虐待的“江南第一琵琶高手”宋印章与被苛刻
					家人逼得离家出走的豪爽厨娘孙三娘,三位姐妹从此结伴而行,终抵东京见识世间繁华。为了不被另攀高枝的欧阳旭从京城赶走,赵盼儿与宋引章、孙三娘一起历尽艰辛,将小小茶坊一步步发展最大的酒楼,揭露了
					负心人的真面目,收获了各自的真挚感情和人生感悟,也为无数平凡女子推开了一扇平等救赎之门。
				</span>
  </p>
</div>
<script type="text/javascript">
  //获取div标签
  var div_1=document.getElementById("div_1")
  //给div_1绑定事件:onmouseover:鼠标移入的事件
  div_1.onmouseover=function(){
    //将p标签显示出来,故需要将display的值设置为block
    document.querySelector("p").style.display="block"
  }
  // onmouseout:鼠标从元素上移开时触发的事件
  div_1.onmouseout=function(){
    //将p标签隐藏,故需要将display的值设置为none
    document.querySelector("p").style.display="none"
  }
  //onmousemove:鼠标在元素上移动时触发的事件
  div_1.onmousemove=function(){
    document.querySelector("p").style.left=event.offsetX+"px"
    document.querySelector("p").style.top=event.offsetY+"px"
  }
</script>
</body>
</html>

6. Writing exception pages

We create an Error.jsp under the web project

The location of Error.jsp is as shown below:

 Display of error page:

The code to implement the error page is as follows:

<html>
<head>
    <title>404</title>
</head>
<body>
<H2>出错了</H2>
<a href="Login.jsp">返回登录界面</a>
</body>
</html>

7. Web.xml configuration Servlet class

    <!--配置Servlet类-->
    <servlet>
        <!-- 起别名 -->
        <servlet-name>login</servlet-name>
        <!-- servlet类所在的位置:类的全类名就是 包名.类名 -->
        <servlet-class>com.hp.Servlet.Login</servlet-class>
    </servlet>
    <!-- Servlet类的映射:Servlet用来处理哪个请求 -->
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

8. Create a user entity class under the bean package

Where to create the user entity class:

 The code in the user entity class is as follows:

public class User {
    private Integer uid;
    private String username;
    private String password;
    private String phone;
    private String address;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

9. Implement JDBC connection method under Util package

Create a JDBCUtil class under the Util package

The location of the JDBCUtil class is as follows:

 The code that implements getting the connection and closing the resource in the JDBCUtil class is as follows:

public class JDBCUtil {
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
    private static String user = "root";
    private static String pwd = "123456";
    private static Connection con = null;
    //测试
    public static void main(String[] args) {
        System.out.println(getCon());
    }
    //获取数据库连接方法
    public static Connection getCon(){
        try {
            //加载驱动
            Class.forName(driver);
            //获取连接
            con = DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回连接
        return con;
    }

    //关闭资源方法
    public static void loginClose(ResultSet rs, PreparedStatement pstm, Connection con){
        try {
            if (rs!=null){
                rs.close();
            }
            if (pstm!=null){
                pstm.close();
            }
            if (con!=null){
                con.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

10. Implement database operations

First, we build a UserDao interface class under the dao package to implement login and registration functions.

The location of the UserDao interface class is as follows:

 The code in the UserDao interface class is as follows:

public interface UserDao {
    //登录方法
    public User login(String username, String password);

    //注册方法
    public int enroll(User user);
}

Then we first build a DaoImpl package in the dao package, and then build a UserDaoImpl class in the impl package to implement database operations.

The location of the UserDaoImpl class is as follows:

 The code in the UserDaoImpl class is as follows:

/**
 * 数据库数据类
 */
public class UserDaoImpl implements UserDao {
    //数据库连接对象
    Connection con = null;//连接对象
    //预处理对象
    PreparedStatement pstm = null;//与处理对象
    //结果集对象
    ResultSet rs = null;//结果集对象
    int row ;//受影响的行数
    //实例化对象
    User register = null;

    //数据库登录操作
    public User login (String username,String password){
        User login = null;
        //下面的代码完成的事情: 需要用户名和密码  返回一个user对象
        try {
            //调用util包下的jdbc连接方法
            con = JDBCUtil.getCon();
            //编写SQL语句
            String sql = "select * from t_user where username = ? and password = ?";
            //预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //传参
            pstm.setObject(1,username);
            pstm.setObject(2,password);
            //获取结果集对象 ,获取结果
            rs = pstm.executeQuery();
            if (rs.next()){
                //实例化对象
                login = new User();
                //获取结果及对象 把数据传入User对象中
                login.setUsername(rs.getString("username"));
                login.setPassword(rs.getString("password"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //调用关闭资源方法
            JDBCUtil.loginClose(rs,pstm,con);
        }
        //返回User结果
        return login;
    }

    //数据库注册操作
    @Override
    public int enroll(User register) {
        //下面的代码完成的事情: 获取用户输入的数据添加到数据库中
        try {
            //调用util包下的jdbc连接方法
            con = JDBCUtil.getCon();
            //编写SQL语句
            String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?);";
            //预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //传参
            pstm.setObject(1,register.getUsername());
            pstm.setObject(2,register.getPassword());
            pstm.setObject(3,register.getPhone());
            pstm.setObject(4,register.getAddress());
            //获取结果集对象 ,获取结果
            row = pstm.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //调用关闭资源的方法
            JDBCUtil.loginClose(null,pstm,con);
        }
        //返回受影响的行数
        return row;
    }
}

11. Login business processing

Create a Login class under the Servlet package to handle the login business

The location of the Login class is as shown below:

 

The code within the Login class is as follows:

/**
 * 登录类
 */
public class Login extends HttpServlet {
    //数据库连接对象
    Connection con = null;
    //预处理对象
    PreparedStatement pstm = null;
    //结果集对象
    ResultSet rs = null;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...get");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...post");
        //1.从请求中获取用户提交的参数(数据)
        request.setCharacterEncoding("UTF-8");//设置请求的编码格式为中文
        String user = request.getParameter("user");//根据表单的name属性获取用户输入的值
        String pwd = request.getParameter("pwd");//根据表单的name属性获取用户输入的值

        System.out.println(user);
        System.out.println(pwd);

        //2.业务处理
        //调用数据库类
        UserDaoImpl userDao =new UserDaoImpl();
        //传参
        User user1 = userDao.login(user,pwd);

        //判断是否有该账号
        if (user1!=null){
            //登录成功跳转登录首页
            response.sendRedirect("ShouYe.jsp");
        }else {
            //登录失败跳转错误页面
            response.sendRedirect("Error.jsp");
        }

    }
}

12. Registration business processing

Create an Enroll class under the Servlet package to handle the login business

The location of the Enroll class is shown in the figure below:

 The code within the Enroll class is as follows:

/**
 * 注册类
 */
//设置当前类用来处理 /enroll 的请求
@WebServlet("/enroll")
public class Enroll extends HttpServlet {
    //数据库连接对象
    Connection con = null;
    //预处理对象
    PreparedStatement pstm = null;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...get");
        //调用doPost方法
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...post");
        //设置请求的编码格式为UTF-8格式
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //设置以文本或网页的形式响应
        response.setContentType("text/html;charset=UTF-8");//已什么样的格式(文本/网页)响应

        //从请求中获取用户提交的参数(数据)
        String zhangh = request.getParameter("zhangh");
        String pwd = request.getParameter("pwd");
        String dell = request.getParameter("dell");
        String address = request.getParameter("address");

        //实例化对象
        User enroll = new User();
        //给实体类user 赋值
        enroll.setUsername(zhangh);
        enroll.setPassword(pwd);
        enroll.setPhone(dell);
        enroll.setAddress(address);

        //实现UserDao接口的UserDaoImpl类
        UserDao userDao = new UserDaoImpl();
        //调用子类接口的enroll方法 返回受影响的行数
        int row = userDao.enroll(enroll);

        //判断受影响的行数大于零注册成功
        if (row>0){
            //注册成功 跳转登录页面
            response.sendRedirect("Login.jsp");
        }else {
            //注册失败 跳转错误页面
            response.sendRedirect("Error.jsp");
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_71385552/article/details/129112409