在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]');
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=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包说明:对应的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>
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习