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', 'admin@atguigu.com');

四、項目實現

 

(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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM