JAVA分页原理(二)——使用SQL实现

JdbcSqlStudentDaoImpl.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;
/**
 * 使用mysql数据库limit关键字实现分页
 * @author yrui
 *
 */
public class JdbcSqlStudentDaoImpl implements StudentDao {

	@Override
	public Pager findStudent(Student searchModel, int pageNum, int pageSize) {
		Pager result = null;
		//存放查询参数
		List paramList = new ArrayList();
		String stuName = searchModel.getStuName();
		int gender = searchModel.getGender();
		
		StringBuilder sql = new StringBuilder("select * from t_student where 1=1");
		StringBuilder countSql = new StringBuilder("select count(id) as totalRecord from t_student where 1=1");
		if(stuName !=null&&!stuName.equals("")){
			sql.append(" and stu_name like ?");
			countSql.append(" and stu_name like ?");
			paramList.add("%"+stuName+"%");
		}
		if(gender==Constant.GENDER_FEMALE||gender==Constant.GENDER_MALE){
			sql.append(" and gender = ?");
			countSql.append(" and gender = ?");
			paramList.add(gender);
		}
		// 起始索引
		int fromIndex = pageSize * (pageNum - 1);
		//使用limit关键字实现分页
		sql.append(" limit "+ fromIndex+","+pageSize);
		
		//存放所有查询出的学生对象
		List studentList = new ArrayList();
		JdbcUtil jdbcUtil = null;
		try {
			jdbcUtil = new JdbcUtil();
			jdbcUtil.getConnection();//获取数据库连接
			//获取总记录数
			List> countResult = jdbcUtil.findResult(countSql.toString(), paramList);
			Map countMap = countResult.get(0);
			int totalRecord = ((Number)countMap.get("totalRecord")).intValue();
			//获取查询的学生记录
			List> studentResult = jdbcUtil.findResult(sql.toString(), paramList);
			if(studentResult!=null){
				for(Map map:studentResult){
					Student s = new Student(map);
					studentList.add(s);
				}
			}
			
			// 获取总页数
			int totalPage = totalRecord / pageSize;
			if (totalRecord % pageSize != 0) {
				totalPage = totalPage + 1;
			}
			//组装pager对象
			result = new Pager<>(pageSize, pageNum, totalRecord, totalPage, studentList);
		} catch (SQLException e) {
			throw new RuntimeException("查询所有数据异常!",e);
		}finally{
			if(jdbcUtil!=null){
				jdbcUtil.releaseConn();//一定要释放资源
			}
		}
		return result;
	}

}
 
  

JdbcSqlStudentServiceImpl.java

package com.imooc.page.service;

import com.imooc.page.dao.JdbcSqlStudentDaoImpl;
import com.imooc.page.dao.StudentDao;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;

public class JdbcSqlStudentServiceImpl implements StudentService {

	private StudentDao studentDao;
	
	public JdbcSqlStudentServiceImpl(){
		//创建service实现类时,初始化dao对象
		studentDao = new JdbcSqlStudentDaoImpl();
	}
	@Override
	public Pager findStudent(Student searchModel, int pageNum, int pageSize) {
		Pager result = studentDao.findStudent(searchModel, pageNum, pageSize);
		return result;
	}
	public StudentDao getStudentDao() {
		return studentDao;
	}
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

}

JdbcSqlServlet.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.JdbcSqlStudentServiceImpl;
import com.imooc.page.service.StudentService;
import com.imooc.page.util.StringUtil;


public class JdbcSqlServlet extends HttpServlet {
	
	private static final long serialVersionUID = -4873699362194465829L;
	private StudentService studentService = new JdbcSqlStudentServiceImpl();
	
	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("jdbcSqlStudent.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 result = studentService.findStudent(searchModel, pageNum, pageSize);
		
		//返回结果到页面
		request.setAttribute("result", result);
		request.setAttribute("stuName", stuName);
		request.setAttribute("gender", gender);
		request.getRequestDispatcher("jdbcSqlStudent.jsp").forward(request, response);
	}

}

引用了github上https://github.com/gbirke/jquery_pagination的分页工具

导入了一个css文件和2个js文件

 

JAVA分页原理(二)——使用SQL实现_第1张图片

jdbcSqlStudent.jsp

<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>



学生信息

<%
	//获取请求上下文
	String context = request.getContextPath();
%>





	
${errorMsg }
姓名   性别   

学生信息列表:

查询的结果不存在
姓名 性别 年龄 家庭地址

好啦,完成啦

JAVA分页原理(二)——使用SQL实现_第2张图片

你可能感兴趣的:(JAVA分页原理(二)——使用SQL实现)