项目目录结构
首先本项目使用到的软件环境有:eclipse jee neon, Tomcat8.5,JDK1.8数据库:mysql。
补充:本项目需要mysql连接jdbc的jar包,以及jstl的jar包。
jstl.jar
mysql-connector-java-5.1.45-bin.jar
standard-1.1.2.jar
数据库,可以直接运行即可
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('蕾姆', 17);
INSERT INTO users(NAME, age) VALUES('艾米莉亚', 17);
1、BaseDao.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
// 数据库驱动类
// 数据库地址
public static final String URL = "jdbc:mysql://localhost:3306/thh";
// 用户名
public static final String USER = "root";
// 密码
public static final String PASSWORD = "tanghh";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// 获得数据库连接
public void getConnection() {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 更新数据
public int executeUpdate(String sql, Object... obj) {
int num = 0;
getConnection();
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i
pstmt.setObject(i + 1, obj[i]);
}
num = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return num;
}
// 查询数据
public ResultSet executeQuery(String sql, Object... obj) {
getConnection();
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i
pstmt.setObject(i + 1, obj[i]);
}
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// 关闭资源
public void closeAll() {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2、UsersDao.java
package com.dao;
import java.util.List;
import com.entity.Users;
public interface UsersDao {
public int addUser(Users u);
public int delUser(int id);
public int updateUser(Users u);
public Users findUserById(int id);
public List getAllUsers();
}
3、UserDaoImpl.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.dao.BaseDao;
import com.dao.UsersDao;
import com.entity.Users;
public class UsersDaoImpl extends BaseDao implements UsersDao {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// 添加用户
@Override
public int addUser(Users u) {
int num = 0;
String sql = "insert into users(name,age) values(?,?)";
try {
num = executeUpdate(sql, u.getName(), u.getAge());
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
// 删除用户
@Override
public int delUser(int id) {
int num = 0;
String sql = "delete from users where id=?";
try {
num = executeUpdate(sql, id);
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
// 更新用户
@Override
public int updateUser(Users u) {
int num = 0;
String sql = "update users set name=?,age=? where id=?";
try {
num = executeUpdate(sql, u.getName(), u.getAge(), u.getId());
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
// 根据id查找
@Override
public Users findUserById(int id) {
Users u = null;
String sql = "select * from users where id=?";
rs = executeQuery(sql, id);
try {
if (rs.next()) {
u = new Users(rs.getInt(1), rs.getString(2), rs.getInt(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
return u;
}
// 查询所有用户
@Override
public List getAllUsers() {
List ulist = new ArrayList();
String sql = "select * from users";
rs = executeQuery(sql);
try {
while (rs.next()) {
Users u = new Users(rs.getInt(1), rs.getString(2), rs.getInt(3));
ulist.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
}
return ulist;
}
}
4、Users.java
package com.entity;
/**
* users表所对应的实体类
*/
public class Users {
// 实体类的属性和表的字段名称一一对应
private int id;
private String name;
private int age;
public Users(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Users() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
5、UsersServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import com.dao.UsersDao;
import com.entity.Users;
public class UsersServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
UsersDao ud = new UsersDaoImpl();
String dos = request.getParameter("do");
if (dos == null || dos.equals("")) {
dos = "index";
}
// 主页
if (dos.equals("index")) {
List ulist = ud.getAllUsers();
session.setAttribute("ulist", ulist);
response.sendRedirect("index.jsp");
return;
}
// 添加页
if (dos.equals("add")) {
String name = request.getParameter("name");
String ages = request.getParameter("age");
int age = Integer.parseInt(ages);
Users u = new Users(0, name, age);
ud.addUser(u);
out.print("");
}
if (dos.equals("del")) {
String ids = request.getParameter("id");
int id = Integer.parseInt(ids);
ud.delUser(id);
out.print("");
return;
}
if (dos.equals("editbefore")) {
String ids = request.getParameter("id");
int id = Integer.parseInt(ids);
Users u = ud.findUserById(id);
session.setAttribute("edituser", u);
response.sendRedirect("edit.jsp");
return;
}
if (dos.equals("edit")) {
String ids = request.getParameter("id");
int id = Integer.parseInt(ids);
String name = request.getParameter("name");
String ages = request.getParameter("age");
int age = Integer.parseInt(ages);
Users u = new Users(id, name, age);
ud.updateUser(u);
out.print("");
return;
}
}
}
6、web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
jdbc
UsersServlet
com.servlet.UsersServlet
UsersServlet
/usersservlet
usersservlet
7、add.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
">
My JSP 'add.jsp' starting page
新增页面
姓名:
年龄:
8、edit.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
">
My JSP 'add.jsp' starting page
修改页面
姓名:
年龄:
9、index.jsp
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
">
My JSP 'index.jsp' starting page
table {
width: 600px;
height: 300px;
}
td {
text-align: center;
}
主页
id
姓名
年龄
操作
$
$
$
修改
onclick="javascript:return confirm('确认删除吗?');">删除新增
10、运行结果
全部用户
修改用户
删除用户
新添用户
恭喜完成!!!
web简书∣一个实用的公众号
领取专属 10元无门槛券
私享最新 技术干货