JDBC(Java Database Connectivity)是Java编程语言中用于与数据库建立连接并进行数据库操作的API(应用程序编程接口)。JDBC允许开发人员连接到数据库,执行各种操作(如插入、更新、删除和查询数据),并检索结果。
JDBC提供了一个标准的方法,使Java应用程序能够与各种类型的数据库进行交互,使其在某种程度上与数据库无关。它是Java中用于数据库连接的基本技术,使开发人员能够构建与数据库交互的强大应用程序。
下面我们通过具体的实验来学习它,主要下面几个部分
。
内容:
一、JDBC快速入门实验
1.创建数据库db_myweb和account表,三个字段:id、name、money
2.创建eclipse项目导入MySQL驱动包
3.编写数据库操作7个步骤代码实现数据更新
4.查看结果
二、利用Junit实现JDBC的增晒改查实验
1.给项目添加JUnit单元测试,创建JDBCTest测试用例类
2.添加5个测试方法分别为:
public void testInsert(){}
public void testUpdate(){}
public void testDelete(){}
public void testFindAll(){}
public void testFind(){}
3.对5个方法测试,并查看测试结果
三、完成SQL注入实验,并对比结果
四、完成转账事务控制实验,并对比结果
五、自定义封装JDBC连接工具类
1.第一代JDBCUtils类封装与测试,查看结果
2.第二代JDBCUtils类封装与测试,查看结果
六、封装增删改查DAO
1.创建tb_user表,字段有:id username password email birthday
2.创建JavaBean:User.java
3.创建工具类JDBCUtils.java
4.创建数据库访问层DAO类封装增删改查代码:UserDao.java
5.利用JUnit对DAO的方法进行单元测试,并查看结果
七、完成网站登录程序实验
1.创建登录页面login.jsp
2.UserDao增加方法按用户名和密码查询方法
3.创建登录功能的LoginServlet.java
4.运行项目,查看效果
OK,话不多说,直接开始!
1.创建数据库db_myweb和account表,三个字段:id、name、money
创建db_myweb数据库:
create database db_myweb charset=utf8;
使用db_myweb数据库:
use db_myweb;
创建表account表,三个字段:id、name、money:
CREATE TABLE `account` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(25) DEFAULT NULL,`money` double DEFAULT NULL,PRIMARY KEY (`id`)
);
2.创建eclipse项目导入MySQL驱动包
创建JDBC web动态工程,lib目录下导入mysql-connector-java-5.1.48.jar 驱动包。
Build Path把sql驱动包加到路径里面。
3.编写数据库操作7个步骤代码实现数据更新
package com.java5678.Demo;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;public class JDBCDemo {public static void main(String[] args) throws Exception {//1. 注册驱动Class.forName("com.mysql.jdbc.Driver");/*2. 获取连接*/String url = "jdbc:mysql://localhost:3306/db_myweb";String username = "root";String password = "root";Connection conn = DriverManager.getConnection(url, username, password);//3. 定义sql/*String sql = "insert into account value('2','li','2')";*/String sql = " update account set money = 2000 where id = 1";/*4. 获取执行sql的对象 Statement*/Statement stmt = conn.createStatement();/*5. 执行sql*/int count = stmt.executeUpdate(sql);//受影响的行数/*6. 处理结果*/System.out.println(count);/*7. 释放资源*/stmt.close();conn.close();}
}
数据库账号密码都是root
4.查看结果
db_myweb数据库里面的account表里面id为一的信息成功从300更新2000:
利用Junit实现JDBC的增删改查实验
1.给项目添加JUnit单元测试,创建JDBCTest测试用例类
创建工具类JDBCUtils:
package chapter02.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
public static Connection getConnection() throws SQLException,ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db_myweb?serverTimezone=UTC";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
public static void release(Statement stmt, Connection conn) {
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
public static void release(ResultSet rs,Statement stmt,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
}
2.添加5个测试方法:
package chapter02.jdbc.example;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;import com.javaweb.bean.user;public class UsersDao {
//添加用户的操作
public boolean insert(user user) {
Connection conn = null;
Statement stmt=null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(user.getBirthday());
String sql = "INSERT INTO tb_user(id,username,password,email,birthday)"+
"VALUES("
+user.getId()
+",'"
+user.getUsername()
+"','"
+user.getPassword()
+"','"
+user.getEmail()
+"','"
+birthday + "')";
System.out.println(sql);
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs,stmt,conn);
}
return false;
}
public ArrayList<user> findAll(){
Connection conn = null;
Statement stmt=null;
ResultSet rs = null;
ArrayList<user> list = new ArrayList<user>();
try {
conn = JDBCUtils.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM tb_user";
rs = stmt.executeQuery(sql);
while(rs.next()) {
user user = new user();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
list.add(user);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt, conn);
}
return null;
}
public user find(int id) {
Connection conn=null;
Statement stmt=null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt=conn.createStatement();
String sql = "SELECT * FROM tb_user WHERE id=" + id;
rs = stmt.executeQuery(sql);
while(rs.next()) {
user user = new user();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
return user;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs,stmt, conn);
}
return null;
}
public boolean delete(int id) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
stmt= conn.createStatement();
String sql = "DELETE FROM tb_user WHERE id=" + id;
int num =stmt.executeUpdate(sql);
if(num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, stmt,conn);
}
return false;
}
public boolean update(user user) {
Connection conn =null;
Statement stmt = null;
ResultSet rs = null;
try {
conn= JDBCUtils.getConnection();
stmt = conn.createStatement();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday =sdf.format(user.getBirthday());
String sql = "UPDATE tb_user set username='"+user.getUsername()
+"',password='"+user.getPassword() + "',email='"
+user.getEmail() + "',birthday='" + birthday
+"'WHERE id=" + user.getId();
int num = stmt.executeUpdate(sql);
if (num > 0) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.release(rs, stmt, conn);
}
return false;
}
}
3.对5个方法测试,并查看测试结果
添加测试类JDBCTest实现向tb_usr插入数据库:
package chapter02.jdbc.example;
import java.util.ArrayList;
import java.util.Date;import com.javaweb.bean.user;@Test
public class JDBCTest {public static void main(String[] args) {//向users表插入一个用户信息UsersDao ud = new UsersDao();user user=new user();user.setId(8);user.setUsername("hfdsdl");user.setPassword("12363");user.setEmail("hl6@sina.com");user.setBirthday(new Date());boolean b= ud.insert(user);System.out.println(b);}}
成功插入数据:
编写测试类FindAllUsersTest,该类用于实现读取tb_user表中所有的数据:
package chapter02.jdbc.example;
import java.util.ArrayList;
import com.javaweb.bean.user;public class FindAllUsersTest {public static void main(String[] args) {UsersDao usersDao = new UsersDao();ArrayList<user> list = usersDao.findAll();for (int i=0; i< list.size(); i++) {System.out.println("第" + (i+1) + "条数据的username的值为:"+list.get(i).getUsername());}}
最后成功读取tb_user表中所有的数据:
编写测试类UpdateUserTest,在该类中实现修改tb_user表中数据的操作:
package chapter02.jdbc.example;
import java.util.Date;
import com.javaweb.bean.user;public class UpdateUserTest {public static void main(String[] args) {UsersDao usersDao = new UsersDao();user user = new user();user.setId(5);user.setUsername("zhaoxiaoliu");user.setPassword("456");user.setEmail("zhaoxiaoliu@sina.com");user.setBirthday(new Date());boolean b=usersDao.update(user);System.out.println(b);}
}
运行结果和查询结果如图所示:
编写测试类DeleteUserTest,该类实现了删除tb_user 表中数据的操作:
package chapter02.jdbc.example;
public class DeleteUserTest {public static void main(String[] args) {UsersDao usersDao = new UsersDao();boolean b = usersDao.delete(5);System.out.println(b);}
}
运行结果和sql查询结果如图所示:
从图中可以看出,users表中id为5的User对象已被成功删除了。至此,使用JDBC对数据库中数据进行增删改查的操作已经完成。
完成SQL注入实验,并对比结果
SQL注入模拟:正常登陆SQL查询:
新建testLogin单元测试:
package com.java5678.Demo;import static org.junit.Assert.*;import java.sql.DriverManager;
import java.sql.ResultSet;import org.junit.Test;import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;public class testLogin {@Testpublic void testLogin() throws Exception {String url = "jdbc:mysql://localhost:3306/db_myweb";String username = "root";String password = "root";Connection conn = (Connection) DriverManager.getConnection(url, username, password);// 接收用户输入 用户名和密码String name = "zl";String pwd = "123456";String sql = "select * from tb_user where username = '"+name+"' and password = '"+pwd+"'";// 获取stmt对象Statement stmt = (Statement) conn.createStatement();// 执行sqlResultSet rs = stmt.executeQuery(sql);// 判断登录是否成功if(rs.next()){System.out.println("登录成功~");}else{System.out.println("登录失败~");}//7. 释放资源rs.close();stmt.close();conn.close();}}
测试成功 :
QL注入模拟:SQL注入SQL查询:
新建单元测试testLogin2单元测试:
package com.java5678.Demo;import static org.junit.Assert.*;import java.sql.DriverManager;
import java.sql.ResultSet;import org.junit.Test;import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;public class testLogin2 {@Test
public void testLogin_Inject() throws Exception {
//2. 获取连接:如果连接的是本机mysql并且端口是默认的 3306 可以简化书写
String url = "jdbc:mysql://localhost:3306/db_myweb";
String username = "root";
String password = "root";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
// 接收用户输入 用户名和密码
String name = "hfkjsfhskj";
String pwd = "' or '1' = '1";
String sql = "select * from tb_user where username = '"+name+"' and password = '"+pwd+"'";
System.out.println(sql);
// 获取stmt对象
Statement stmt = (Statement) conn.createStatement();
// 执行sql
ResultSet rs = stmt.executeQuery(sql);// 判断登录是否成功
if(rs.next()){
System.out.println("登录成功~");
}else{
System.out.println("登录失败~");
}//7. 释放资源
rs.close();
stmt.close();
conn.close();
}
}
运行testLogin2单元测试发现sql注入成功!
完成转账事务控制实验,并对比结果
创建JDBCDemo3_Connection java类:
开启事务:setAutoCommit(boolean autoCommit):true为自动提交事务,false为手动提交事务,即为开启事务
提交事务:commit()
回滚事务:rollback()
package com.java5678.Demo;import java.sql.DriverManager;import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;public class JDBCDemo3_Connection {
public static void main(String[] args) throws Exception {
//1. 注册驱动
//Class.forName("com.mysql.jdbc.Driver");
//2. 获取连接:如果连接的是本机mysql并且端口是默认的 3306 可以简化书写
String url = "jdbc:mysql:///db_myweb?useSSL=false";
String username = "root";
String password = "root";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
//3. 定义sql
String sql1 = "update account set money = 3000 where id = 1";
String sql2 = "update account set money = 3000 where id = 2";
//4. 获取执行sql的对象 Statement
Statement stmt = (Statement) conn.createStatement();
try {
// 开启事务
conn.setAutoCommit(false);
//5. 执行sql
int count1 = stmt.executeUpdate(sql1);//受影响的行数
//6. 处理结果
System.out.println(count1);
//5. 执行sql
int count2 = stmt.executeUpdate(sql2);//受影响的行数
//6. 处理结果
System.out.println(count2);// 提交事务
conn.commit();
} catch (Exception throwables) {
// 回滚事务
conn.rollback();
throwables.printStackTrace();
}
//7. 释放资源
stmt.close();
conn.close();
}
}
运行结果:
成功完成转账事务:
自定义封装JDBC连接工具类
1.第一代JDBCUtils类封装与测试,查看结果
在包com.javaweb.utils下面创建testJdbcUtils1类:
package com.javaweb.utils;
import java.sql.*;
public class testJdbcUtils1 {public static void main(String[] args) throws Exception {Connection conn = JDBCUtils.getconnection();String sql="update account set money = ? where id = ?";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, "20000");pstm.setString(2, "1");int count=pstm.executeUpdate();JDBCUtils.close( null,pstm, conn);System.out.println(count);}
}
2.第二代JDBCUtils类封装与测试,查看结果
在src下创建数据库连接配置文件:jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_myweb?useSSL=false
user=root
password=root
创建JDBCUtils2类:
package com.javaweb.utils;
import java.io.FileReader;
import java.sql.*;
import java.util.Properties;public class JDBCUtils2 {private static String driver;private static String url;private static String user;private static String password;
static {try {// 1. 创建Properties集合类。Properties properties = new Properties();// 2. 加载文件properties.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath()));driver = properties.getProperty("driver");url = properties.getProperty("url");user = properties.getProperty("user");password = properties.getProperty("password");// 注册驱动Class.forName(driver);} catch (Exception e) {e.printStackTrace();}}
public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password);}// 释放资源public static void close(ResultSet rs, PreparedStatement pstm, Connection conn) {try {if (rs != null) {rs.close();}if (pstm != null) {pstm.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}
}
第二代JDBCUtils测试:
package com.javaweb.utils;
import java.sql.*;
public class testJdbcUtils2 {
public static void main(String[] args) throws Exception {
Connection conn = JDBCUtils2.getConnection();
String sql = "update account set money = ? where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setDouble(1, 5000);
pstmt.setInt(2, 1);
int count = pstmt.executeUpdate();
System.out.println(count);
}
}
测试结果成功:
封装增删改查DAO
1.创建tb_user表,字段有:id username password email birthday
在MySQL中使用一个名称为db_myweb的数据库,然后在该数据库中创建一个tb_user表,再向表中插入3条数据。
Use db_myweb;
CREATE TABLE tb_user(id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(40),password VARCHAR(40),email VARCHAR(60),birthday DATE
)CHARACTER SET utf8 COLLATE utf8_general_ci;
插入数据:
INSERT INTO tb_user(username,password ,email,birthday) VALUES('zs','123456','zs@sina.com','1980-12-04');
INSERT INTO tb_user(username,password ,email,birthday) VALUES('lisi','123456','lisi@sina.com','1981-12-04');
INSERT INTO tb_user(username,password ,email,birthday) VALUES('wangwu','123456','wangwu@sina.com','1979-12-04');
2.创建JavaBean:User.java
在src目录下,新建一个名称为chapter02.jdbc.example的包
创建JavaBean,User类的具体实现方式如下:
package com.javaweb.bean;import java.util.Date;public class user {private int id;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;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}private String username;private String password;private String email;private Date birthday;}
3.创建数据库访问层DAO类封装增删改查代码:UserDao.java
package chapter02.jdbc.example;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;import com.javaweb.bean.user;public class UsersDao {//添加用户的操作public boolean insert(user user) {Connection conn = null;Statement stmt=null;ResultSet rs = null;try {conn = JDBCUtils.getConnection();stmt = conn.createStatement();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String birthday = sdf.format(user.getBirthday());String sql = "INSERT INTO tb_user(id,username,password,email,birthday)"+"VALUES("+user.getId()+",'"+user.getUsername()+"','"+user.getPassword()+"','"+user.getEmail()+"','"+birthday + "')";System.out.println(sql);int num = stmt.executeUpdate(sql);if (num > 0) {return true;}return false;} catch (Exception e) {e.printStackTrace();} finally {JDBCUtils.release(rs,stmt,conn);}return false;}public ArrayList<user> findAll(){Connection conn = null;Statement stmt=null;ResultSet rs = null;ArrayList<user> list = new ArrayList<user>();try {conn = JDBCUtils.getConnection();stmt = conn.createStatement();String sql = "SELECT * FROM tb_user";rs = stmt.executeQuery(sql);while(rs.next()) {user user = new user();user.setId(rs.getInt("id"));user.setUsername(rs.getString("username"));user.setPassword(rs.getString("password"));user.setEmail(rs.getString("email"));user.setBirthday(rs.getDate("birthday"));list.add(user);}return list;} catch (Exception e) {e.printStackTrace();} finally {JDBCUtils.release(rs, stmt, conn);}return null;}public user find(int id) {Connection conn=null;Statement stmt=null;ResultSet rs = null;try {conn = JDBCUtils.getConnection();stmt=conn.createStatement();String sql = "SELECT * FROM tb_user WHERE id=" + id;rs = stmt.executeQuery(sql);while(rs.next()) {user user = new user();user.setId(rs.getInt("id"));user.setUsername(rs.getString("username"));user.setPassword(rs.getString("password"));user.setEmail(rs.getString("email"));user.setBirthday(rs.getDate("birthday"));return user;}return null;} catch (Exception e) {e.printStackTrace();} finally {JDBCUtils.release(rs,stmt, conn);}return null;}public boolean delete(int id) {Connection conn = null;Statement stmt = null;ResultSet rs = null;try {conn = JDBCUtils.getConnection();stmt= conn.createStatement();String sql = "DELETE FROM tb_user WHERE id=" + id;int num =stmt.executeUpdate(sql);if(num > 0) {return true;}return false;} catch (Exception e) {e.printStackTrace();} finally {JDBCUtils.release(rs, stmt,conn);}return false;}public boolean update(user user) {Connection conn =null;Statement stmt = null;ResultSet rs = null;try {conn= JDBCUtils.getConnection();stmt = conn.createStatement();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String birthday =sdf.format(user.getBirthday());String sql = "UPDATE tb_user set username='"+user.getUsername()+"',password='"+user.getPassword() + "',email='"+user.getEmail() + "',birthday='" + birthday+"'WHERE id=" + user.getId();int num = stmt.executeUpdate(sql);if (num > 0) {return true;}return false;} catch (Exception e) {e.printStackTrace();}finally {JDBCUtils.release(rs, stmt, conn);}return false;}
}
4.利用JUnit对DAO的方法进行单元测试,并查看结果
创建测试类JDBCTESTl,利用JUnit对DAO-insert方法添加tb_user表中的数据:
package chapter02.jdbc.example;import java.util.Date;import com.javaweb.bean.user;@Test
public class JDBCTest {public static void main(String[] args) {//向users表插入一个用户信息UsersDao ud = new UsersDao();user user=new user();user.setId(4);user.setUsername("xiaoli");user.setPassword("00000");user.setEmail("h23526456@qq.com");user.setBirthday(new Date());boolean b= ud.insert(user);System.out.println(b);}}
测试结果:
创建测试类JDBCTEST03,利用JUnit对DAO-findAll方法根据ID查询tb_user表中数据:
package chapter02.jdbc.example;import java.util.ArrayList;import com.javaweb.bean.user;public class FindAllUsersTest {public static void main(String[] args) {UsersDao usersDao = new UsersDao();ArrayList<user> list = usersDao.findAll();for (int i=0; i< list.size(); i++) {System.out.println("第" + (i+1) + "条数据的username的值为:"+list.get(i).getUsername());}}}
测试结果,成功查询出tb_user表中所有username值:
创建测试类JDBCTEST03,利用JUnit对DAO-find方法根据ID查询tb_user表中数据:
我们根据ID查询tb_user表中ID为13的数据库信息:
package chapter02.jdbc.example;import static org.junit.Assert.*;import org.junit.Test;import com.javaweb.bean.user;public class JDBCTEST03 {@Testpublic void testFind() throws Exception {UsersDao dao= new UsersDao();user user=dao.find(13);System.out.println("id为13的User对象的name值为:"+user.getUsername());}}
测试结果:
成功通过ID查询rb_user表中ID为13的username信息
创建测试类JDBCTEST04,利用JUnit对DAO-update方法方法根据ID更新tb_user表中数据:
package chapter02.jdbc.example;import java.util.Date;import org.junit.Test;import com.javaweb.bean.user;public class JDBCTEST04 {@Testpublic void testUpdate() throws Exception {UsersDao dao= new UsersDao();user user=new user();user.setId(13);user.setUsername("项秀才让");user.setPassword("abc");user.setEmail("123456@sina.com");user.setBirthday(new Date());boolean b=dao.update(user);System.out.println(b);}}
测试结果:
成功修改ID为13的数据库记录信息!
创建测试类JdbcTest01,利用DAO-delete方法删除tb_user表中的数据
package chapter02.jdbc.example;
import org.junit.jupiter.api.Test;
class JdbcTest01 {@Testpublic void testDelete() {UsersDao dao= new UsersDao();boolean b=dao.delete(8);System.out.println(b);}
}
测试结果和sql查询结果:
完成网站登录程序实验
1.创建登录页面login.jsp
在web目录下创建一个名称为login的JSP文件,在该文件中添加用于用户登录时输入用户信息的表单元素。
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/myweb/LoginServlet" method="post">
用户名:<input type="text" name="username"> <br>
密 码:<input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
</body>
</html>
2.UserDao增加方法按用户名和密码查询方法
// 根据username,password查找指定的user
public boolean findByUsernameAndPassword(String username,String password){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获得数据的连接
conn = JDBCUtils.getConnection();
// 发送SQL语句
String sql = "select * from tb_user where username=? and password=?";
// 获得PreparedStatement对象
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
// 处理结果集
if (rs.next())
return true;
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, pstmt, conn);
}
return false;
}
3.创建登录功能的LoginServlet.java
package com.javaweb.servlet;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class LoginServlet*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
/*** */private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();String username=request.getParameter("username");String password=request.getParameter("password");if(username!=null&&password!=null&&!username.equals("")&&!password.equals("")) {UserDao dao=new UserDao();boolean b=dao.findByUsernameAndPassword(username, password);if(b)out.print("欢迎登录!");elseout.print("用户名或密码不正确!"); }elseout.print("用户名或密码不能为空!"); }}
4.运行项目,查看效果
不输入用户名和密码时候登录:
输入错误密码时: