数据库:
项目结构:
jdbc.properties
jdbc.username=root
jdbc.password=1234
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/demo
Student.java
package com.imooc.page.model;
import java.io.Serializable;
import java.util.Map;
public class Student implements Serializable {
private static final long serialVersionUID = -7476381137287496245L;
private int id;
private String stuName;
private int age;
private int gender;
private String address;
public Student() {
super();
}
public Student(int id, String stuName, int age, int gender, String address) {
super();
this.id = id;
this.stuName = stuName;
this.age = age;
this.gender = gender;
this.address = address;
}
public Student(Map<String,Object> map){
this.id = (int)map.get("id");
this.stuName = (String)map.get("stu_name");
this.age = (int)map.get("age");
this.gender = (int)map.get("gender");
this.address = (String)map.get("address");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [id=" + id + ", stuName=" + stuName + ", age=" + age + ", gender=" + gender + ", address="
+ address + "]";
}
}
Pager.java
package com.imooc.page.model;
import java.io.Serializable;
import java.util.List;
public class Pager<T> implements Serializable {
private static final long serialVersionUID = -8741766802354222579L;
private int pageSize;// 每页显示多少条记录
private int currentPage;// 当前页
private int totalRecord;// 一共多少条记录
private int totalPage;// 一共多少页记录
private List<T> dataList;// 要显示的数据
public Pager(int pageNum, int pageSize, List<T> sourceList) {
if (sourceList == null) {
return;
}
// 总记录条数
this.totalRecord = sourceList.size();
this.pageSize = pageSize;
// 获取总页数
this.totalPage = this.totalRecord / this.pageSize;
if (this.totalRecord % this.pageSize != 0) {
this.totalPage = this.totalPage + 1;
}
// 当前第几页数据
this.currentPage = this.totalPage < pageNum ? this.totalPage : pageNum;
// 起始索引
int fromIndex = this.pageSize * (this.currentPage - 1);
// 结束索引
int toIndex = this.pageSize * this.currentPage > this.totalRecord ? this.totalRecord
: this.pageSize * this.currentPage;
this.dataList = sourceList.subList(fromIndex, toIndex);
}
public Pager() {
super();
}
public Pager(int pageSize, int currentPage, int totalRecord, int totalPage, List<T> dataList) {
super();
this.pageSize = pageSize;
this.currentPage = currentPage;
this.totalRecord = totalRecord;
this.totalPage = totalPage;
this.dataList = dataList;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
}
JdbcUtil.java
package com.imooc.page.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class JdbcUtil {
private static String USERNAME;
private static String PASSWORD;
// 数据库的驱动信息
private static String DRIVER;
// 访问数据库的地址
private static String URL;
private Connection connection;
// sql语句的执行对象
private PreparedStatement pstmt;
// 返回的结果集合
private ResultSet resultSet;
static{
//加载数据库配置信息,并给相关的属性赋值
loadConfig();
}
/**
* 加载数据库配置信息,并给相关属性赋值
*/
public static void loadConfig(){
try{
InputStream inStream = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
Properties prop = new Properties();
prop.load(inStream);
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
DRIVER = prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
}catch(Exception e){
throw new RuntimeException("读取数据库配置文件异常!",e);
}
}
public JdbcUtil() {
}
/**
* 获取数据库连接
*
* @return
*/
public Connection getConnection() {
try {
Class.forName(DRIVER);// 注册驱动
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
throw new RuntimeException("get connection error!");
}
return connection;
}
/**
*
* @param sql语句
* @param params
* 执行参数
* @return
* @throws SQLException
*/
public boolean updateByPreparedStatement(String sql, List<?> params) throws SQLException {
boolean flag = false;
int result = -1;// 表示用户执行添加删除和修改的时候所影响数据库的行数
pstmt = connection.prepareStatement(sql);
int index = 1;
// 填充sql语句中的占位符
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}
/**
* 执行查询操作
*
* @param sql
* sql语句
* @param params
* 执行参数
* @return
* @throws SQLException
*/
public List<Map<String, Object>> findResult(String sql, List<?> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
// getMetaData()获取结果集的所有字段的描述
ResultSetMetaData metaData = resultSet.getMetaData();
// 得到数据集的列数
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 释放资源
*/
public void releaseConn() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JdbcUtil jdbcUtil = new JdbcUtil();
jdbcUtil.getConnection();
try {
List<Map<String, Object>> result = jdbcUtil.findResult(
"select * from t_student", null);
for (Map<String, Object> m : result) {
System.out.println(m);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtil.releaseConn();
}
}
}
StudentDao.java
package com.imooc.page.dao;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public interface StudentDao {
/**
* 根据查询条件,查询学生分页信息
* @param searchModel 封装查询条件
* @param pageNum 查询第几页数据
* @param pageSize 每页显示多少条记录
* @return 查询结果
*/
public Pager<Student> findStudent(Student searchModel,
int pageNum,int pageSize);
}
SublistStudentDaoImpl.java
package com.imooc.page.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.util.JdbcUtil;
public class SublistStudentDaoImpl implements StudentDao {
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) {
List<Student> allStudentList = getAllStudent(searchModel);
Pager<Student> pager = new Pager<Student>(pageNum,pageSize,allStudentList);
return pager;
}
/**
* 模仿获取所有数据
* @param searchModel 查询参数
* @return
*/
private List<Student> getAllStudent(Student searchModel){
List<Student> result = new ArrayList<Student>();
List<Object> paramList = new ArrayList<Object>();
String stuName = searchModel.getStuName();
int gender = searchModel.getGender();
StringBuilder sql = new StringBuilder("select * from t_student where 1=1");
if(stuName !=null&&!stuName.equals("")){
sql.append(" and stu_name like ?");
paramList.add("%"+stuName+"%");
}
if(gender==Constant.GENDER_FEMALE||gender==Constant.GENDER_MALE){
sql.append(" and gender = ?");
paramList.add(gender);
}
JdbcUtil jdbcUtil = null;
try {
jdbcUtil = new JdbcUtil();
jdbcUtil.getConnection();//获取数据库连接
List<Map<String,Object>> mapList = jdbcUtil.findResult(sql.toString(), paramList);
if(mapList!=null){
for(Map<String,Object> map:mapList){
Student s = new Student(map);
result.add(s);
}
}
} catch (SQLException e) {
throw new RuntimeException("查询所有数据异常!",e);
}finally{
if(jdbcUtil!=null){
jdbcUtil.releaseConn();//一定要释放资源
}
}
return result;
}
}
StudentService.java:
package com.imooc.page.service;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public interface StudentService {
/**
* 根据查询条件,查询学生分页信息
* @param searchModel 封装查询条件
* @param pageNum 查询第几页数据
* @param pageSize 每页显示多少条记录
* @return 查询结果
*/
public Pager<Student> findStudent(Student searchModel,
int pageNum,int pageSize);
}
SublistStudentServiceImpl.java
package com.imooc.page.service;
import com.imooc.page.dao.StudentDao;
import com.imooc.page.dao.SublistStudentDaoImpl;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public class SublistStudentServiceImpl implements StudentService{
private StudentDao studentDao;
public SublistStudentServiceImpl(){
//创建service实现类时,初始化dao对象
studentDao = new SublistStudentDaoImpl();
}
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) {
Pager<Student> result = studentDao.findStudent(searchModel, pageNum, pageSize);
return result;
}
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
Constant.java
package com.imooc.page;
public class Constant {
public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;
public static final int DEFAULT_PAGE_SIZE = 5;
public static final int DEFAULT_PAGE_NUM = 1;
public static final int DEFAULT_GENDER = 0;
}
StringUtil.java
package com.imooc.page.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
/**
* 检验字符串是否是大于0的数字
* @param string
* @return
*/
public static boolean isNum(String string){
Pattern pattern = Pattern.compile("[1-9]{1}\\d*");
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
}
SublistServlet.java
package com.imooc.page.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.service.StudentService;
import com.imooc.page.service.SublistStudentServiceImpl;
import com.imooc.page.util.StringUtil;
public class SublistServlet extends HttpServlet {
private static final long serialVersionUID = 1513900937858484233L;
private StudentService studentService = new SublistStudentServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//接收request里的参数
String stuName = request.getParameter("stuName");
int gender = Constant.DEFAULT_GENDER;
String genderStr = request.getParameter("gender");
if(genderStr!=null&&!"".equals(genderStr.trim())){
gender = Integer.parseInt(genderStr);
}
//校验pageNum参数输入的合法性
String pageNumStr = request.getParameter("pageNum");
if(pageNumStr!=null&&!StringUtil.isNum(pageNumStr)){
request.setAttribute("errorMsg", "参数传输错误");
request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);
return;
}
int pageNum = Constant.DEFAULT_PAGE_NUM;
if(pageNumStr!=null&&!"".equals(pageNumStr.trim())){
pageNum = Integer.parseInt(pageNumStr);
}
int pageSize = Constant.DEFAULT_PAGE_SIZE;
String pageSizeStr = request.getParameter("pageSize");
if(pageSizeStr!=null&&!"".equals(pageSizeStr.trim())){
pageSize = Integer.parseInt(pageSizeStr);
}
//组装查询条件
Student searchModel = new Student();
searchModel.setStuName(stuName);
searchModel.setGender(gender);
//调用service获取查询结果
Pager<Student> result = studentService.findStudent(searchModel, pageNum, pageSize);
//返回结果到页面
request.setAttribute("result", result);
request.setAttribute("stuName", stuName);
request.setAttribute("gender", gender);
request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);
}
}
sublistStudent.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生信息</title>
</head>
<%
//获取请求上下文
String context = request.getContextPath();
%>
<script type="text/javascript">
//当前显示第几页数据
var currentPage = ${result.currentPage};
var totalPage = ${result.totalPage}
function submitForm(actionUrl){
var formElement = document.getElementById("stuForm");
formElement.action = actionUrl;
formElement.submit();
}
function firstPage(){
if(currentPage == 1){
alert("已经是第一页数据");
return false;
}else{
submitForm("<%=context%>/sublist/SublistServlet?pageNum=1");
return true;
}
}
function nextPage(){
if(currentPage == totalPage){
alert("已经是最后一页数据");
return false;
}else{
submitForm("<%=context%>/sublist/SublistServlet?pageNum="+(currentPage+1));
return true;
}
}
function previousPage(){
if(currentPage == 1){
alert("已经是第一页数据");
return false;
}else{
submitForm("<%=context%>/sublist/SublistServlet?pageNum="+(currentPage-1));
return true;
}
}
function lastPage(){
if(currentPage == totalPage){
alert("已经是最后一页数据");
return false;
}else{
submitForm("<%=context%>/sublist/SublistServlet?pageNum=${result.totalPage}");
return true;
}
}
function initPage(){
var genderRequest = "${gender}";
var genderVal = 0;
var genderElement = document.getElementById("gender");
if(genderRequest!=""){
genderVal = parseInt(genderRequest);
}
var options = genderElement.options;
var i=0;
for(i=0;i<options.length;i++){
if(options[i].value==genderVal){
options[i].selected = true;
break;
}
}
}
</script>
<body onload="initPage();">
<div style="margin-left:100px;margin-top:100px;">
<div>
<font color="red">${errorMsg }</font>
</div>
<div>
<form action="<%=context %>/sublist/SublistServlet" id="stuForm" method="post">
姓名
<input type="text" name="stuName" id="stu_name" style="width:120px;" value="${stuName }">
性别
<select name="gender" id="gender" style="width:80px">
<option value="0">全部</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
<input type="submit" value="查询">
</form>
</div>
<br>
学生信息列表:<br>
<br>
<!-- 后台返回结果为空 -->
<c:if test="${fn:length(result.dataList) eq 0}">
<span>查询的结果不存在</span>
</c:if>
<!-- 后台返回结果不为空 -->
<c:if test="${fn:length(result.dataList) gt 0}"> <!-- 大于0 -->
<table border="1px" cellspacing="0px" style="border-collapse: collapse">
<thead>
<tr height="30">
<th width="130">姓名</th>
<th width="130">性别</th>
<th width="130">年龄</th>
<th width="130">家庭地址</th>
</tr>
</thead>
<c:forEach items="${result.dataList}" var="student">
<tr>
<td><c:out value="${student.stuName }"></c:out></td>
<td>
<c:if test="${student.gender eq 1 }">男</c:if>
<c:if test="${student.gender eq 2 }">女</c:if>
</td>
<td><c:out value="${student.age }"></c:out></td>
<td><c:out value="${student.address }"></c:out></td>
</tr>
</c:forEach>
</table>
<br>共${result.totalRecord}条记录 共${result.totalPage}页 当前第${result.currentPage }页
<a href="#" onclick="firstPage();">首页</a>
<a href="#" onclick="previousPage();">上一页</a>
<a href="#" onclick="nextPage();">下一页</a>
<a href="#" onclick="lastPage();">尾页</a>
</c:if>
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
<display-name>pager</display-name>
<servlet>
<servlet-name>SublistServlet</servlet-name>
<servlet-class>com.imooc.page.servlet.SublistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SublistServlet</servlet-name>
<url-pattern>/sublist/SublistServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
完成啦!!
启动tomcat,然后输入网址http://localhost:8080/pager/sublist/sublistStudent.jsp