1. 程式人生 > 實用技巧 >JavaWeb之登入功能的實現

JavaWeb之登入功能的實現

一、專案說明

  本專案實現了登入功能。在主頁點選“我要登入”連結,跳轉到登入頁面。在登入頁面,輸入使用者名稱和密碼,點選登入,提交給LoginServlet做處理。查詢資料庫表中的資料,如果使用者名稱和密碼正確,則重定向到登入成功頁面;如果使用者名稱或密碼錯誤,則請求轉發到登入頁面。

二、開發環境

  開發工具:spring-tool-suite-4

  資料庫:Mysql

  伺服器:tomcat7

  jdk:1.8

三、資料庫的結構和資料

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50716
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50716
File Encoding         : 65001

Date: 2020-07-30 10:28:07
*/ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `email` varchar
(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES ('1', 'admin', '123456', '[email protected]');

四、專案實現

 

(1)在bean包下,實現了User實體類,定義使用者物件的私有成員變數,並用get和set方法進行封裝

,有參和無參和構造方法,重寫toString方法

package com.atguigu.bean;

public class User {
    
    private int id;
    private String username;
    private String password;
    private String email;
    
    public User() {
        super();
    }

    public User(int id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }

}

(2)在dao包下,定義UserDao介面,用UserDaoImpl類繼承這個介面,並重寫介面中的checkUsernameAndPassword方法,該方法可根據使用者名稱和密碼在資料庫中查詢對應的記錄。有,則返回一個User物件,無則返回null

UserDao介面程式碼如下

package com.atguigu.dao;

import com.atguigu.bean.User;

public interface UserDao {

    /**
     * 根據使用者名稱和密碼在資料庫中查詢對應的記錄
     * @param username
     * @param Password
     * @return User 有此記錄 null 無此記錄
     */
    User checkUsernameAndPassword(String username,String Password);
}

UserDaoImpl程式碼如下

package com.atguigu.dao.impl;

import com.atguigu.bean.User;
import com.atguigu.dao.BasicDao;
import com.atguigu.dao.UserDao;

public class UserDaoImpl implements UserDao {

    //建立BasicDao物件
    BasicDao basicDao = new BasicDao();
    
    @Override
    public User checkUsernameAndPassword(String username, String password) {
        //寫sql語句
        String sql = "select id,username,password,email from users where username = ? and password = ?";
        User user = basicDao.getBean(User.class, sql, username,password);
        return user;
    }

}

BasicDao類提供了對資料庫進行增刪改查的Dao,程式碼如下

package com.atguigu.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.atguigu.utils.JDBCUtils;

public class BasicDao {
    /*
     * 提供了對資料庫進行增刪改查的Dao
     */
    
    private QueryRunner queryRunner = new QueryRunner();
    
    /**
     * 通用的增刪改的方法
     * @param sql
     * @param params
     * @return
     */
    public int update(String sql,Object... params) {
        //獲取連線
        Connection connection = JDBCUtils.getConnection();
        int count = 0;
        try {
            count = queryRunner.update(connection, sql, params);
        }catch(SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.releaseConnection(connection);
        }
        return count;
    }
    
    /**
     * 獲取一個物件的方法
     * @param <T>
     * @param type
     * @param sql
     * @param params
     * @return
     */
    public <T> T getBean(Class<T> type,String sql,Object... params) {
        //獲取連線
        Connection connection = JDBCUtils.getConnection();
        T t = null;
        try {
            t = queryRunner.query(connection, sql, new BeanHandler<T>(type), params);
        }catch(SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.releaseConnection(connection);
        }
        return t;
    }
}

(3)在servlet包下,定義了一個Servlet,即LoginServlet,使用doGet和doPost方法處理使用者的登入請求

package com.atguigu.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.bean.User;
import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;

/**
 * 處理使用者登入的Servlet
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲取使用者名稱和密碼
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //建立UserDao物件
        UserDao userDao = new UserDaoImpl();
        //呼叫UserDao裡面驗證使用者名稱和密碼的方法
        User user = userDao.checkUsernameAndPassword(username, password);
        if(user != null) {
            //使用者名稱和密碼正確
            response.sendRedirect(request.getContextPath()+"/pages/login_success.html");
        }else {
            //使用者名稱或密碼不正確
            //獲取轉發器
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/pages/login.html");
            //進行請求轉發
            requestDispatcher.forward(request, response);
        }
    }

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

}

(4)test包,負責進行單元測試

ConnectionTest類測試資料庫是否連線成功

package com.atguigu.test;

import java.sql.Connection;

import org.junit.jupiter.api.Test;

import com.atguigu.utils.JDBCUtils;

class ConnectionTest {

    @Test
    void test() {
        Connection connection = JDBCUtils.getConnection();
        System.out.println(connection);
    }

}

UserdaoTest類測試UserDao介面的方法能否實現

package com.atguigu.test;

import org.junit.jupiter.api.Test;

import com.atguigu.bean.User;
import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;

class UserDaoTest {

    UserDao userDao = new UserDaoImpl();
    
    @Test
    void testCheckUsernameAndPassword() {
        User user = userDao.checkUsernameAndPassword("admin", "123456");
        System.out.println(user);
    }

}

(5)在utils包下,定義JDBCUtils工具類,用於獲取和釋放Connection連線

package com.atguigu.utils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/*
 * 獲取連線和釋放連線的工具類
 */

public class JDBCUtils {
    private static DataSource dataSource;
    
    static {
        try {
            //1、讀取druid.properties檔案
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            
            //2、連線連線池
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    //獲取連線
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        }catch(SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    //釋放連線
    public static void releaseConnection(Connection connection) {
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

(6)在config原始檔下,定義druid配置檔案,配置資料庫連線池的相關屬性

# key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username=root
password=root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000

(7)jar包說明,可在maven中央倉庫下載相應的jar包,複製到WEB-INF下的lib資料夾下

(8)前端頁面說明

index,html頁面程式碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- base標籤中的href屬性可以讓當前頁面中的相對路徑變為絕對路徑 -->
<base href="http://localhost:8080/Web_Ex/">
</head>
<body>
    <!-- 
        以 / 開頭的路徑就是絕對路徑
        絕對路徑中的 / 代表什麼
            如果路徑由瀏覽器解析,那麼 / 就代表http://localhost:8080/
            哪些路徑由瀏覽器解析?
                1)HTML標籤中的路徑,如a標籤中href屬性中的路徑,form標籤中action屬性中的路徑等
                2)重定向中的路徑
            如果路徑由伺服器解析,那麼 / 就代表http://localhost:8080/Web_Ex/
            哪些路徑由伺服器解析?
                1)web.xml配置檔案中的url-pattern標籤中的路徑
                2)轉發中的路徑
     -->
    <a href="pages/login.html">我要登入</a><br><br>
    <a href="#">我要註冊</a>
</body>
</html>

login.html頁面程式碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    body{
        background-color: pink;
    }
</style>
<!-- base標籤中的href屬性可以讓當前頁面中的相對路徑變為絕對路徑 -->
<base href="http://localhost:8080/Web_Ex/">
</head>
<body>
    <h1>歡迎登入</h1>
    <form action="LoginServlet" method="post">
        使用者名稱稱:<input type="text" name="username" /><br>
        使用者密碼:<input type="password" name="password" /><br>
        <input type="submit" value="登入">
    </form>
</body>
</html>

login_success.html程式碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- base標籤中的href屬性可以讓當前頁面中的相對路徑變為絕對路徑 -->
<base href="http://localhost:8080/Web_Ex/">
</head>
<body>
    <h1>登入成功</h1>
    <a href="index.html">回首頁</a>
</body>
</html>