小言_互联网的博客

简单的jsp+servlet+jdbc+mysql实现用户增删改查-一抹茶-csdn

645人阅读  评论(0)

jsp+servlet+jdbc+mysql实现用户增删改查

项目下载地址…里面包含了项目文件,jar,bootstrap,jquery,sql
也可以联系957406675 QQ群获取下载

  1. 运行环境
    .jdk1.8.0_102
    .eclipse Neon.2 Release (4.6.2)
    .Tomcat 8.0.52
    .mysql 5 7

  2. 项目准备
    .创建web项目


    .架包

    .目录结构

    .数据库创建

    user表

    .连接数据库的工具类DBUtils.java

package com.zsx.utils;

import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class DBUtils {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static Connection conn = null;

	static {
		Properties properties = new Properties(); // 创建一个properties对象
		Reader inReader; // 一个reader属性;

		try {
			String path = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
			inReader = new FileReader(path); // 用这个方法获取properties配置文件;
			properties.load(inReader); // 加载load内部的地址;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 通过properties.getProperty("driver");方法获取值
		driver = properties.getProperty("driver");
		url = properties.getProperty("url");
		user = properties.getProperty("user");
		password = properties.getProperty("password");
	}

	/**
	 * 打开数据库连接
	 * 
	 * @return
	 */
	public static Connection open() {
		try {
			Class.forName(driver);
			System.out.println("连接成功......");
			return DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			System.out.println("连接数据库失败....");
		}
		return null;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @return
	 */
	public static Connection close() {
		if (conn != null) {
			try {
				conn.close();// 关闭数据库
				System.out.println("关闭...");
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("数据库关闭失败...");
			}
		}
		return null;
	}
}

需要在src下新建一个 jdbc.properties

内容如下,
.driver:驱动
.url:数据库的地址jdbc:mysql://localhost:3306/+这里数据库名?字符集
.user:数据库用户名
.password:数据库密码

 driver=com.mysql.jdbc.Driver
 url=jdbc:mysql://localhost:3306/jspdemo?useUnicode=true&characterEncoding=utf8
 user=root 
 password=root
  1. 进入主题
    实体类User.java
package com.zsx.bean;

public class User {
	private Integer id;
	private String userName;
	private String password;

	public User(Integer id, String userName, String passwrod) {
		super();
		this.id = id;
		this.userName = userName;
		this.password = passwrod;
	}

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPasswrod() {
		return password;
	}

	public void setPasswrod(String passwrod) {
		this.password = passwrod;
	}

}

.servlet 编写
添加
AddServlet.java

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 添加数据
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (username != null && password != null) {
			Connection conn = DBUtils.open(); /// 获得数据库连接
			String sql = "insert into user(user_name, password) values(?,?);";

			try {
				PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译
				prtmt.setString(1, username); // 给第一个? 传值
				prtmt.setString(2, password); // 给第二个? 传值
				int resInt = prtmt.executeUpdate(); // 如果添加成功返回影响数
				request.setAttribute("resInt", resInt);
				request.getRequestDispatcher("/findAllServlet").forward(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				DBUtils.close(); // 关闭数据库连接
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

DelServlet.java

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class DelServlet
 */
@WebServlet("/DelServlet")
public class DelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 删除数据
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id"); // 传入id;
		if (id != null) {
			Connection conn = DBUtils.open();// 获得数据连接
			String sql = "delete from user where id = ?";
			try {
				PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译

				prtmt.setString(1, id); // 给id赋值
				int resInt = prtmt.executeUpdate(); // 执行sql返回影响行数;
				request.setAttribute("resInt", resInt);
				request.getRequestDispatcher("/findAllServlet").forward(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				DBUtils.close(); // 关闭数据库连接
			}

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

UpdateServlet.java

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 更新数据
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (id != null && username != null || password != null) {
			// 获得数据库连接
			Connection conn = DBUtils.open();
			String sql = "update user set user_name=?,password=? where id=?"; // sql语句

			try {
				PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译语句

				prtmt.setString(1, username); // 给第一个? 添加数据
				prtmt.setString(2, password); // 给第二个? 添加数据
				prtmt.setString(3, id); // 给第三个? 添加数据

				int resInt = prtmt.executeUpdate(); // 执行
				request.setAttribute("resInt", resInt); // 返回影响的行数
				request.getRequestDispatcher("/findAllServlet").forward(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				DBUtils.close(); // 关闭数据库连接
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

FindAllServlet.java

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsx.bean.User;
import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class FindAllServlet
 */
@WebServlet("/findAllServlet")
public class FindAllServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 查询所有用户
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<User> userList = new ArrayList<User>(); // 创建一个list集合,用于装user集合
		Connection conn = DBUtils.open(); // 打开数据库连接
		String sql = " select id,user_name,password from user ;";

		try {
			PreparedStatement prtmt = conn.prepareStatement(sql);
			ResultSet rs = prtmt.executeQuery();

			while (rs.next()) {
				int id = rs.getInt("id");
				String username = rs.getString("user_name");
				String password = rs.getString("password");
				User user = new User(); /// 实例化user
				user.setId(id);
				user.setUserName(username);
				user.setPasswrod(password);
				userList.add(user);
			}
			request.setAttribute("userList", userList);
			request.getRequestDispatcher("/user_list.jsp").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtils.close(); // 关闭数据库连接
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

.前端页面

用了bootstrap前端框架美化界面,在使用bootstrap之前需要引入jquery框架,在后面我会细说

bootstrap下载地址…

jquery下载地址…

将两个插件引入项目

将下载来的bootstrap拷贝到WebContext下如上图
将jquery-1.11.1.js放入js文件夹下

.编写欢迎页面
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎页面</title>
</head>
<body>
	<center>
		<h1>
			<a href="findAllServlet">用户信息</a>
		</h1>
	</center>
</body>
</html>

user_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<%=path%>/resource/bs/js/jquery-1.11.1.js"></script>	<!-- 引入jquery -->
<link rel="stylesheet" href="<%=path%>/resource/bs/css/bootstrap.css"> <!-- 引入bootstrap.css -->
<script src="<%=path%>/resource/bs/js/bootstrap.min.js"></script><!-- 引入bootstrap.min.js -->
<title>用户列表</title>
</head>
<body>
	<section class="container">
		<div class="row">
			<div class="col-md-3">
				<button class="btn btn-danger" data-toggle="modal"
					data-target="#addModal">新增</button>
			</div>

		</div>
		<table class="table table-striped table-bordered table-hover">
			<th>ID</th>
			<th>用户名</th>
			<th>密码</th>
			<th>操作</th>
			<c:forEach items="${ userList }" var="list">
				<tr>
					<td>${list.id }</td>
					<td>${list.userName }</td>
					<td>${list.passwrod }</td>
					<td colspan="2"><button class="btn btn-primary edBtn"
							data-toggle="modal" data-target="#edModal" value="${list.id }" n="${ list.userName}" p="${list.passwrod }">编辑</button>
						<button class="btn btn-danger delBtn" data-toggle="modal"
							data-target=".delModal" value="${list.id }">删除</button></td>
				</tr>
			</c:forEach>
		</table>
	</section>
</body>

<div class="modal fade delModal" tabindex="-1" role="dialog"
	aria-labelledby="gridSystemModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="gridSystemModalLabel">提示</h4>
			</div>
			<div class="modal-body">
				<h4>真的不要了吗?</h4>
			</div>
			<div class="modal-footer">
				<form action="DelServlet">
					<input id="delid" name="id" value="" hidden>
					<button type="button" class="btn btn-primary" data-dismiss="modal">留着</button>
					<button type="submit" class="btn btn-danger">删了</button>
				</form>
			</div>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<!-- 编辑模态框 -->
<div class="modal fade" id="edModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="UpdateServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" id="username"
							value="${user.userName }" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" id="password"
							value="${user.password }" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">更新</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- 添加模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="addServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" value="" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" value="" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">添加</button>
				</div>
			</form>
		</div>
	</div>
</div>


<script type="text/javascript">
	// 删除按钮
	$(".delBtn").on("click", function() {
		$("#delid").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给删除模态框的<input name="id"
	});
	// 编辑按钮
	$(".edBtn").on("click", function() {
		$("#edId").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给编辑模态框的<input name="id"
		$("#username").val($(this).attr("n"));	//取按钮上的自定义属性值
		$("#password").val($(this).attr("p"));	//取按钮上的自定义属性值
	});
</script>
</html>

.启动项目

欢迎页

用户信息展示

新增用户

更新用户

删除用户

如果这些功能都实现了,恭喜你!!!

这是彩蛋
百度网盘地址:
链接:https://pan.baidu.com/s/15Tbe7Mu0UVu4TG7uqO3NHg
提取码:uk4h

新增条件查询:

由于很多的同学都在问如何做查询,现在给同学们添加上

FindConditionServlet.java

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsx.bean.User;
import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class FindAllServlet
 */
@WebServlet("/findConditionServlet")
public class FindConditionServlet extends HttpServlet {
   
	private static final long serialVersionUID = 1L;
	private String userName = null;

	/**
	 * 按条件查询用户
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
   
		List<User> userList = new ArrayList<User>(); // 创建一个list集合,用于装user集合
		Connection conn = DBUtils.open(); // 打开数据库连接
		String sql = " select id,user_name,password from user where 1=1 ";
		
		// 获取姓名
		userName = request.getParameter("userName");
		if (null != userName) {
   
			sql += " and user_name like " + "concat('%','" + userName + "','%')";
		}

		try {
   
			PreparedStatement prtmt = conn.prepareStatement(sql);
			ResultSet rs = prtmt.executeQuery();

			while (rs.next()) {
   
				int id = rs.getInt("id");
				String username = rs.getString("user_name");
				String password = rs.getString("password");
				User user = new User(); /// 实例化user
				user.setId(id);
				user.setUserName(username);
				user.setPasswrod(password);
				userList.add(user);
			}
			request.setAttribute("userList", userList);
			request.getRequestDispatcher("/user_list.jsp").forward(request, response);
		} catch (SQLException e) {
   
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
   
			DBUtils.close(); // 关闭数据库连接
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
   
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

user_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<%=path%>/resource/bs/js/jquery-1.11.1.js"></script>	<!-- 引入jquery -->
<link rel="stylesheet" href="<%=path%>/resource/bs/css/bootstrap.css"> <!-- 引入bootstrap.css -->
<script src="<%=path%>/resource/bs/js/bootstrap.min.js"></script><!-- 引入bootstrap.min.js -->
<title>用户列表</title>
</head>
<body>
	<section class="container">
		<br>
		<div class="row">
			<div class="col-md-4">
				<form class="form-inline" action="findConditionServlet">
					<label for="userName">用户名:</label>
					<input id="userName" class="form-control" name="userName" value="">
					<button type="submit" class="btn btn-primary">搜索</button>
				</form>
			</div>
		</div>
		<br>
		<div class="row">
			<div class="col-md-3">
				<button class="btn btn-danger" data-toggle="modal"
					data-target="#addModal">新增</button>
			</div>

		</div>
		<br>
		<table class="table table-striped table-bordered table-hover">
			<th>ID</th>
			<th>用户名</th>
			<th>密码</th>
			<th>操作</th>
			<c:forEach items="${ userList }" var="list">
				<tr>
					<td>${list.id }</td>
					<td>${list.userName }</td>
					<td>${list.passwrod }</td>
					<td colspan="2"><button class="btn btn-primary edBtn"
							data-toggle="modal" data-target="#edModal" value="${list.id }" n="${ list.userName}" p="${list.passwrod }">编辑</button>
						<button class="btn btn-danger delBtn" data-toggle="modal"
							data-target=".delModal" value="${list.id }">删除</button></td>
				</tr>
			</c:forEach>
		</table>
	</section>
</body>

<div class="modal fade delModal" tabindex="-1" role="dialog"
	aria-labelledby="gridSystemModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="gridSystemModalLabel">提示</h4>
			</div>
			<div class="modal-body">
				<h4>真的不要了吗?</h4>
			</div>
			<div class="modal-footer">
				<form action="DelServlet">
					<input id="delid" name="id" value="" hidden>
					<button type="button" class="btn btn-primary" data-dismiss="modal">留着</button>
					<button type="submit" class="btn btn-danger">删了</button>
				</form>
			</div>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<!-- 编辑模态框 -->
<div class="modal fade" id="edModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="UpdateServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" id="username"
							value="${user.userName }" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" id="password"
							value="${user.password }" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">更新</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- 添加模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="addServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" value="" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" value="" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">添加</button>
				</div>
			</form>
		</div>
	</div>
</div>


<script type="text/javascript">
	// 删除按钮
	$(".delBtn").on("click", function() {
    
		$("#delid").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给删除模态框的<input name="id"
	});
	// 编辑按钮
	$(".edBtn").on("click", function() {
    
		$("#edId").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给编辑模态框的<input name="id"
		$("#username").val($(this).attr("n"));	//取按钮上的自定义属性值
		$("#password").val($(this).attr("p"));	//取按钮上的自定义属性值
	});
</script>
</html>

添加 FindConditionServlet.java 和 修改 user_list.jsp 就好了

简单分页

创建分页对象
Page.java

package com.zsx.bean;

import java.util.List;

public class Page<T> {
   
    /**
     * 构造参数
     * @param currentPage  页面传入的当前页
     * @param pageSize   每页显示的条数
     * @param totalCount  数据库查询的总记录数
     */
    public Page(Integer currentPage, Integer pageSize, Integer totalCount){
   
        this.currentPage = currentPage;
        this.pageSize = (pageSize == null ? this.pageSize : pageSize);
        this.totalCount = totalCount;
        this.previousPage = (currentPage == 1 ? 1 : currentPage-1);
        this.totalPage = (totalCount % this.pageSize == 0 ? totalCount / this.pageSize : totalCount / this.pageSize + 1);
        this.nextPage = (currentPage == totalPage) ? totalPage : (currentPage + 1);
        this.startIndex =(currentPage - 1) * this.pageSize + 1;
        this.endIndex = currentPage * this.pageSize;
    }
    /**
     * 当前页(由页面传递)
     */
    private Integer currentPage;
 
    /**
     * 每页显示的数量默认为10
     */
    private Integer pageSize = 10;
 
    /**
     * 上一页
     * prePage = curPage ==1 ? 1 : curPage-1
     * 举例
     * 		2  -- 1
     * 		3  -- 2
     * 		4  -- 3
     */
    private Integer previousPage;
 
    /**
     * 下一页
     * 	举例:
     * 	nextPage=curPage==totalPage?totalPage:(curPage+1)
     * 	curPage   totalPage  nextPage
     * 		1         3         2
     */
    private Integer nextPage;
 
    /**
     * 总页数
     * pageCount(每页显示的条数)   total(总记录数)   totalpage
     *       10                   20             3
     */
    private Integer totalPage;
 
    /**
     * 总记录数(从数据库查询)
     */
    private Integer totalCount;
 
    /**
     * 开始索引
     * curPage    pageCount  start-end
     * 	  1           10         1-10
     * 	  2           10         11-20
     * 							 (curPage-1)*pageCount+1  curPage*pageCount
     */
    private Integer startIndex;
 
    /**
     * 结束索引
     * @return
     */
    private Integer endIndex;
 
    /**
     * 查询最终查询的数据
     */
    private List<T> data;
 
    public Integer getCurrentPage() {
   
        return currentPage;
    }
 
    public void setCurrentPage(Integer currentPage) {
   
        this.currentPage = currentPage;
    }
 
    public Integer getPageSize() {
   
        return pageSize;
    }
 
    public void setPageSize(Integer pageSize) {
   
        this.pageSize = pageSize;
    }
 
    public Integer getPreviousPage() {
   
        return previousPage;
    }
 
    public void setPreviousPage(Integer previousPage) {
   
        this.previousPage = previousPage;
    }
 
    public Integer getNextPage() {
   
        return nextPage;
    }
 
    public void setNextPage(Integer nextPage) {
   
        this.nextPage = nextPage;
    }
 
    public Integer getTotalPage() {
   
        return totalPage;
    }
 
    public void setTotalPage(Integer totalPage) {
   
        this.totalPage = totalPage;
    }
 
    public Integer getTotalCount() {
   
        return totalCount;
    }
 
    public void setTotalCount(Integer totalCount) {
   
        this.totalCount = totalCount;
    }
 
    public List<T> getData() {
   
        return data;
    }
 
    public void setData(List<T> data) {
   
        this.data = data;
    }
 
    public Integer getStartIndex() {
   
        return startIndex;
    }
 
    public void setStartIndex(Integer startIndex) {
   
        this.startIndex = startIndex;
    }
 
    public Integer getEndIndex() {
   
        return endIndex;
    }
 
    public void setEndIndex(Integer endIndex) {
   
        this.endIndex = endIndex;
    }
    
}

分页的servlet

package com.zsx.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsx.bean.Page;
import com.zsx.bean.User;
import com.zsx.utils.DBUtils;

/**
 * Servlet implementation class FindAllServlet
 */
@WebServlet("/findPageConditionServlet")
public class FindPageConditionServlet extends HttpServlet {
   
	private static final long serialVersionUID = 1L;
	private String userName = null;
	private Integer currentPage = 1;
	private Integer pageSize = 10;

	/**
	 * 按条件查询用户
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
   
		List<User> userList = new ArrayList<User>(); // 创建一个list集合,用于装user集合
		Connection conn = DBUtils.open(); // 打开数据库连接
		String sql = " select id,user_name,password from user where 1=1 ";
		String sqlCount = " select count(id) count from user where 1=1 ";

		// 获取姓名
		userName = request.getParameter("userName");
		// 分页
		currentPage = Integer.parseInt(request.getParameter("currentPage"));
		pageSize = Integer.parseInt(request.getParameter("pageSize"));

		if (null != userName) {
   
			String whereString = " and user_name like " + "concat('%','" + userName + "','%')";
			sql += whereString;
			sqlCount += whereString;
		}

		currentPage = currentPage != null ? currentPage : 1;
		pageSize = pageSize != null ? pageSize : 20;
		long idx = (currentPage - 1) * pageSize;
		if (pageSize != -1) {
   
			// 分页sql
			sql += " limit " + idx + "," + pageSize;
		}

		try {
   
			PreparedStatement prtmt = conn.prepareStatement(sql);
			ResultSet rs = prtmt.executeQuery();

			while (rs.next()) {
   
				int id = rs.getInt("id");
				String username = rs.getString("user_name");
				String password = rs.getString("password");
				User user = new User(); /// 实例化user
				user.setId(id);
				user.setUserName(username);
				user.setPasswrod(password);
				userList.add(user);
			}

		} catch (SQLException e) {
   
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
   
			DBUtils.close(); // 关闭数据库连接
		}

		Connection connCount = DBUtils.open(); // 打开数据库连接
		// 查询数量
		try {
   
			PreparedStatement prtmtCount = connCount.prepareStatement(sqlCount);
			ResultSet countResultSet = prtmtCount.executeQuery();
			
			countResultSet.next();
			Page<User> page = new Page<User>(currentPage, pageSize, countResultSet.getInt(1));
			page.setData(userList);
			
			request.setAttribute("pageInfo", page);
			request.getRequestDispatcher("/user_list.jsp").forward(request, response);
		} catch (SQLException e) {
   
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
   
			DBUtils.close(); // 关闭数据库连接
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
   
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		doGet(request, response);
	}

}

user_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<%=path%>/resource/bs/js/jquery-1.11.1.js"></script>	<!-- 引入jquery -->
<link rel="stylesheet" href="<%=path%>/resource/bs/css/bootstrap.css"> <!-- 引入bootstrap.css -->
<script src="<%=path%>/resource/bs/js/bootstrap.min.js"></script><!-- 引入bootstrap.min.js -->
<title>用户列表</title>
</head>
<body>
	<section class="container">
		<br>
		<div class="row">
			<div class="col-md-4">
				<form class="form-inline" action="findConditionServlet">
					<label for="userName">用户名:</label>
					<input id="userName" class="form-control" name="userName" value="">
					<button type="submit" class="btn btn-primary">搜索</button>
				</form>
			</div>
		</div>
		<br>
		<div class="row">
			<div class="col-md-3">
				<button class="btn btn-danger" data-toggle="modal"
					data-target="#addModal">新增</button>
			</div>

		</div>
		<br>
		<table class="table table-striped table-bordered table-hover">
			<th>ID</th>
			<th>用户名</th>
			<th>密码</th>
			<th>操作</th>
			<c:forEach items="${ pageInfo.data }" var="list">
				<tr>
					<td>${list.id }</td>
					<td>${list.userName }</td>
					<td>${list.passwrod }</td>
					<td colspan="2"><button class="btn btn-primary edBtn"
							data-toggle="modal" data-target="#edModal" value="${list.id }" n="${ list.userName}" p="${list.passwrod }">编辑</button>
						<button class="btn btn-danger delBtn" data-toggle="modal"
							data-target=".delModal" value="${list.id }">删除</button></td>
				</tr>
			</c:forEach>
		</table>
		<!-- 分页 -->
		<nav aria-label="Page navigation">
		  <ul class="pagination">
		    <li>
		      <a href="findPageConditionServlet?currentPage=${pageInfo.previousPage}&pageSize=${pageInfo.pageSize}" aria-label="Previous">
		        <span aria-hidden="true">上一页</span>
		      </a>
		    </li>
		    <li>
		      <a href="findPageConditionServlet?currentPage=${pageInfo.nextPage}&pageSize=${pageInfo.pageSize}" aria-label="Next">
		        <span aria-hidden="true">下一页</span>
		      </a>
		    </li>
		    <li><a>当前页:${pageInfo.currentPage},总数:${pageInfo.totalCount},页数:${pageInfo.totalPage}</a></li>
		  </ul>
		</nav>
	</section>
</body>

<div class="modal fade delModal" tabindex="-1" role="dialog"
	aria-labelledby="gridSystemModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="gridSystemModalLabel">提示</h4>
			</div>
			<div class="modal-body">
				<h4>真的不要了吗?</h4>
			</div>
			<div class="modal-footer">
				<form action="DelServlet">
					<input id="delid" name="id" value="" hidden>
					<button type="button" class="btn btn-primary" data-dismiss="modal">留着</button>
					<button type="submit" class="btn btn-danger">删了</button>
				</form>
			</div>
		</div>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<!-- 编辑模态框 -->
<div class="modal fade" id="edModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="UpdateServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" id="username"
							value="${user.userName }" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" id="password"
							value="${user.password }" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">更新</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- 添加模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog"
	aria-labelledby="edModal">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="exampleModalLabel">用户信息</h4>
			</div>
			<form action="addServlet" method="post">
				<div class="modal-body">
					<input id="edId" name="id" value="" hidden>
					<div class="form-group">
						<label for="username" class="control-label">用户名:</label> <input
							type="text" name="username" class="form-control" value="" required>
					</div>
					<div class="form-group">
						<label for="password" class="control-label">密 码:</label> <input
							type="password" name="password" class="form-control" value="" required>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="submit" class="btn btn-primary">添加</button>
				</div>
			</form>
		</div>
	</div>
</div>


<script type="text/javascript">
	// 删除按钮
	$(".delBtn").on("click", function() {
    
		$("#delid").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给删除模态框的<input name="id"
	});
	// 编辑按钮
	$(".edBtn").on("click", function() {
    
		$("#edId").val($(this).val());	// 获取当前点击按钮的值value值,并赋值给编辑模态框的<input name="id"
		$("#username").val($(this).attr("n"));	//取按钮上的自定义属性值
		$("#password").val($(this).attr("p"));	//取按钮上的自定义属性值
	});
</script>
</html>


转载:https://blog.csdn.net/weixin_43760328/article/details/84559006
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场