一、前期准备
二、数据库方面
use javaweb;
drop table if exists dept;
create table dept(
deptno int primary key,
dname varchar(255),
loc varchar(255)
)charset=utf8;
insert into dept(deptno, dname, loc) values(10, '销售部', '北京');
insert into dept(deptno, dname, loc) values(20, '研发部', '上海');
insert into dept(deptno, dname, loc) values(30, '技术部', '广州');
insert into dept(deptno, dname, loc) values(40, '媒体部', '深圳');
三、JDBC工具类封装
- jdbc配置文件(resources包中的jdbc1.properties)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb
user=root
password=123456
- jdbc工具类
package com.xh.oa2.utils;
import java.sql.*;
import java.util.ResourceBundle;
/**
* JDBC工具类
*/
public class DBUtil {
//静态变量,类加载时执行
//属性资源文件绑定
private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc1");
//根据属性配置文件key获取value
private static String driver = bundle.getString("driver");
private static String url = bundle.getString("url");
private static String user = bundle.getString("user");
private static String password = bundle.getString("password");
static {
//注册驱动,只需要注册一次就够了,放在静态代码块中,DBUtil类加载时执行
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return conn 连接对象
* @throws SQLException
*/
public static Connection getConnection()throws SQLException{
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
* 释放资源
* @param conn 连接对象
* @param ps 数据库操作对象
* @param rs 结果集对象
*/
public static void close(Connection conn, Statement ps, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
四、Servlet+jsp修改oa项目
1.编写登录界面(index.jsp)
<%@page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录界面</title>
</head>
<body>
<h1 align="center">登录界面</h1>
<hr>
<div align="center">
<form action="<%=request.getContextPath()%>/user/login" method="post" >
<p>用户名:<input type="text" name="username" /></p>
<p>密 码:<input type="password" name="password" /></p>
<input type="submit" value="登录" />
</form>
</div>
</body>
</html>
网页展示结果
2. 编写UserServlet类使登录连接数据库
数据库
use javaweb;
drop table if exists t_user;
CREATE TABLE t_user(
id INT PRIMARY KEY auto_increment,
username VARCHAR(255),
upassword VARCHAR(255)
)charset=utf8;
INSERT INTO t_user(username,password) VALOES('admin','123456');
INSERT INTO t_user(username,password) VALUES('zhangsan','123456');
UserServlet类
package com.xh.oa2.web.action;
import com.xh.oa2.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.