您好,登錄后才能下訂單哦!
這篇文章主要介紹“怎么用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', 'admin@atguigu.com');
4.項目實施
(1)在bean包中,我們實現了User實體類,定義了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包中定義了User dao接口,使用User daoimpl類繼承該接口,重寫了接口中的checkUsernameAndPassword方法。該方法可以根據用戶名和密碼查詢數據庫中的相應記錄。如果是,則返回一個 User 對象;否則返回 null
用戶道接口代碼如下
package com.atguigu.dao;import com.atguigu.bean.User;public interface UserDao { /** * Query the corresponding records in the database according to the user name and password * @param username * @param Password * @return User This record is null, but there is no such record */ 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 { //establish BasicDao object BasicDao basicDao = new BasicDao(); @Override public User checkUsernameAndPassword(String username, String password) { //write sql sentence 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 is provided to add, delete and modify the database */ private QueryRunner queryRunner = new QueryRunner(); /** * General method of adding, deleting and modifying * @param sql * @param params * @return */ public int update(String sql,Object... params) { //Get connection 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; } /** * Method to get an object * @param <T> * @param type * @param sql * @param params * @return */ public <T> T getBean(Class<T> type,String sql,Object... params) { //Get connection 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 s that handle user login */public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get user name and password String username = request.getParameter("username"); String password = request.getParameter("password"); //establish UserDao object UserDao userDao = new UserDaoImpl(); //call UserDao The password and user name verification method User user = userDao.checkUsernameAndPassword(username, password); if(user != null) { //The user name and password are correct response.sendRedirect(request.getContextPath()+"/pages/login_success.html"); }else { //Username or password incorrect //Get transponder RequestDispatcher requestDispatcher = request.getRequestDispatcher("/pages/login.html"); //Forward request requestDispatcher.forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
(4) 測試包,負責單元測試
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包下定義了JDBC utils工具類,用于獲取和釋放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;/* * Tool class for getting and releasing connections */public class JDBCUtils { private static DataSource dataSource; static { try { //1,read druid.properties file Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2,Connection pool dataSource = DruidDataSourceFactory.createDataSource(pro); }catch(Exception e) { e.printStackTrace(); } } //Get connection public static Connection getConnection() { Connection connection = null; try { connection = dataSource.getConnection(); }catch(SQLException e) { e.printStackTrace(); } return connection; } //Release the connection public static void releaseConnection(Connection connection) { if(connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
(6)在config源文件中,定義druid配置文件,配置數據庫連接池的相關屬性
# key=valuedriverClassName=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包說明:對應的jar包可以從maven中央倉庫下載,復制到WEB-INF下的lib文件夾下
(8)首頁說明
索引,html頁面代碼
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><!-- base In the label href Property makes the relative path in the current page an absolute path --><base href="http://localhost:8080/Web_Ex/"></head><body> <!-- with / The first path is the absolute path In absolute path / What does it stand for If the path is resolved by the browser, then / On behalf of http://localhost:8080/ Which paths are resolved by the browser? 1)HTML The path in the label, such as a In the label href The path in the property, form In the label action Path in attribute, etc 2)Paths in redirection If the path is resolved by the server, then / On behalf of http://localhost:8080/Web_Ex/ Which paths are resolved by the server? 1)web.xml In the configuration file url-pattern Path in label 2)Path in forwarding --> <a href="pages/login.html">I want to log in</a><br><br> <a href="#">I want to register</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 In the label href Property makes the relative path in the current page an absolute path --><base href="http://localhost:8080/Web_Ex/"></head><body> <h1>Welcome to login</h1> <form action="LoginServlet" method="post"> User name:<input type="text" name="username" /><br> User password:<input type="password" name="password" /><br> <input type="submit" value="Sign in"> </form></body></html>
login_success.html 代碼
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><!-- base In the label href Property makes the relative path in the current page an absolute path --><base href="http://localhost:8080/Web_Ex/"></head><body> <h1>Login successful</h1> <a href="index.html">Home </a></body></html>
關于“怎么用JavaWeb實現登錄功能”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。