一.开发图示

1.1图解

Java连接 active mq_java

1.2包图

 

二.代码实现

需求:实现分页查询

2.1JavaBean

package work.itcase.entity;
/**
 * javaBean   实体类
 * @author Administrator
 *
 */
public class Employee {
	private int empId; // 员工id
	private String empName; // 员工名称
	private int deptid; // 部门id

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public int getDeptid() {
		return deptid;
	}

	public void setDeptid(int deptid) {
		this.deptid = deptid;
	}

	public Employee(int empId,String empName, int deptid) {
		super();
		this.empId = empId;
		this.empName = empName;
		this.deptid = deptid;

	}

	public Employee() {

	}

	@Override
	public String toString() {
		return "Employee [empId=" + empId + ", empName=" + empName
				+ ", deptid=" + deptid + "]";
	}

	

}

2.2dao数据访问层接口

package work.itcase.dao;

import work.itcase.entity.Employee;
import work.itcase.utils.PageBean;

/**
 * 数据访问层
 * @author Administrator
 *
 */
public interface EmployeeDao {
	/* 分页查询数据 */
	public void getAll(PageBean<Employee> pb);

	/* 查询总记录 */
	public int getTotalCount();
}

2.3分页参数的封装

package work.itcase.utils;

import java.util.List;

/**
 * 分页参数的封装
 * 
 * @author Administrator
 * 
 * @param <T>
 */

public class PageBean<T> {
	private int currentPage = 1; // 当前页,默认显示第一页
	private int pageCount = 4; // 每页显示的行数(查询返回的行数), 默认每页显示4行
	private int totalCount; // 总记录数
	private int totalPage; // 总页数 = 总记录数 / 每页显示的行数 (+ 1)
	private List<T> pageData;

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	// 返回总页数
	public int getTotalpage() {
		if (totalCount % pageCount == 0) {
			totalPage = totalCount / pageCount;
		} else {
			totalPage = totalCount / pageCount + 1;
		}
		return totalPage;

	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public List<T> getPageData() {
		return pageData;
	}

	public void setPageData(List<T> pageData) {
		this.pageData = pageData;
	}

	public int getTotalPage() {
		return totalPage;
	}

}

2.4dao数据访问层接口实现

package work.itcase.daoimpl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import work.itcase.dao.EmployeeDao;
import work.itcase.entity.Employee;
import work.itcase.utils.JdbcUtils;
import work.itcase.utils.PageBean;

/**
 * 数据访问层实现
 * 
 * @author Administrator
 * 
 */
public class EmployeeDaoImpl implements EmployeeDao {

	@Override
	public void getAll(PageBean<Employee> pb) {
		// 1. 查询总记录; 设置到pb对象中
		int totalCount = this.getTotalCount();
		pb.setTotalCount(totalCount);
		/*
		 * 分页查询 考虑因素 1.当前页面是首页点击 上一页 报错 2.当前页面是末页点击 下一页 报错
		 * 
		 * 解决 : 1.如果当前页<= 0; 当前页面设置为1 2.如果当前页面>最大页面数; 将当前页面设置为最大页数
		 */
		// 判断
		if (pb.getCurrentPage() <= 0) {
			pb.setCurrentPage(1); // 把当前页设置为1
		} else if (pb.getCurrentPage() > pb.getTotalPage()) {
			// 把当前页设置为最大页数
			pb.setCurrentPage(pb.getTotalPage());
		}
		// 2. 获取当前页: 计算查询的起始行、返回的行数
		int currentPage = pb.getCurrentPage();
		int index = (currentPage - 1) * pb.getPageCount(); // 查询的起始行
		int count = pb.getPageCount(); // 查询返回的行数

		try {
			// 3.分页查询数据; 把查询到的数据设置到pb对象中
			String sql = "select * from employee limit ?,?";

			// 得到QueryRunner对象
			QueryRunner qr = JdbcUtils.getQueryRuner();
			// 根据当前页,查询当前页数据(一页数据)
			List<Employee> pageData = qr
					.query(sql, new BeanListHandler<Employee>(Employee.class),
							index, count);

			// 设置到对象中
			pb.setPageData(pageData);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Override
	public int getTotalCount() {
		String sql = "select count(*) from employee";
		try {
			// 创建QueryRunner对象
			QueryRunner qr = JdbcUtils.getQueryRuner();
			// 执行查询, 返回结果的第一行的第一列
			Long count = qr.query(sql, new ScalarHandler<Long>());
			return count.intValue();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}

2.5业务逻辑层接口

package work.itcase.service;

import work.itcase.entity.Employee;
import work.itcase.utils.PageBean;
/**
 * 业务逻辑层接口设计
 * @author Administrator
 *
 */
public interface EmployeeService {
	/**
	 * 分页查询数据
	 */
	public void getAll(PageBean<Employee> pb);
}

2.6业务逻辑层j接口实现

package work.itcase.serviceimpl;

import work.itcase.dao.EmployeeDao;
import work.itcase.daoimpl.EmployeeDaoImpl;
import work.itcase.entity.Employee;
import work.itcase.service.EmployeeService;
import work.itcase.utils.PageBean;

/**
 * 业务逻辑层实现
 * 
 * @author Administrator
 * 
 */
public class EmployeeServiceImpl implements EmployeeService {
	// 创建dao实例
	private EmployeeDao employ = new EmployeeDaoImpl();

	@Override
	public void getAll(PageBean<Employee> pb) {
		try {
			employ.getAll(pb);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}

2.7控制器

package work.itcase.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 work.itcase.entity.Employee;
import work.itcase.service.EmployeeService;
import work.itcase.serviceimpl.EmployeeServiceImpl;
import work.itcase.utils.PageBean;
/**
 * 4.开发控制器
 * @author Administrator
 *
 */
public class IndexServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	// 1.创建Service实例
	
	private EmployeeService service = new EmployeeServiceImpl();
	// 跳转资源
	
	private String uri;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码格式
		request.setCharacterEncoding("utf-8");
		try {
			// 1.获取 当前页面 参数:(第一次访问当前页为null)
			String currPage = request.getParameter(" currPage");

			// 判断
			if (currPage == null || "".equals(currPage.trim())) {
				currPage = "1"; // 第一次访问,设置当前页为1;
			}
			// 转换
			int currentPage = Integer.parseInt(currPage);

			// 2. 创建PageBean对象,设置当前页参数; 传入service方法参数
			PageBean<Employee> pageBean = new PageBean<Employee>();
			pageBean.setCurrentPage(currentPage);

			// 3. 调用service
			service.getAll(pageBean); // 【pageBean已经被dao填充了数据】

			// 4. 保存pageBean对象,到request域中
			request.setAttribute("pageBean", pageBean);
			// 5. 跳转
			uri = "/WEB-INF/list.jsp";
		} catch (NumberFormatException e) {
			e.printStackTrace();
			// 出现错误,跳转到错误页面;给用户友好提示
			uri = "/error/error.jsp";
		}
		request.getRequestDispatcher(uri).forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

2.8Jdbc工具类

package work.itcase.utils;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 工具类 1.初始化c3p0连接池 2.创建Dbutils核心工具对象
 * 
 * @author Administrator
 */
public class JdbcUtils {
	/*
	 * 1.初始化池c3p0连接池
	 */
	private static DataSource dataSource;
	static {
		dataSource = new ComboPooledDataSource();
	}

	/*
	 * 2.创建Dbutils核心工具类对象
	 */
	public static QueryRunner getQueryRuner() {
		/*
		 * 创建QueryRunner对象,传入连接池对象
		 *  在创建QueryRunner对象的时候,如果传入了数据源对象;
		 * 那么在使用QueryRunner对象方法的时候,就不需要传入连接对象;
		 *  会自动从数据源中获取连接(不用关闭连接)
		 */
		return new QueryRunner(dataSource);
	}
}

2.9c3p0连接池

<c3p0-config>
	<default-config>
	<!--连接数据库 -->
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/demo01?characterEncoding=utf8
		</property>
		<!--数据库驱动-->
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<!--用户名。Default: null -->
		<property name="user">root</property>
		<!--密码。Default: null -->
		<property name="password">0000</property>
		<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
		<property name="initialPoolSize">3</property>
		<!--连接池中保留的最大连接数。Default: 15 -->
		<property name="maxPoolSize">6</property>
		<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
		<property name="maxIdleTime">1000</property>
	</default-config>


	<named-config name="oracle_config">
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/demo01?characterEncoding=utf8</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">0000</property>
		<property name="initialPoolSize">3</property>
		<property name="maxPoolSize">6</property>
		<property name="maxIdleTime">1000</property>
	</named-config>


</c3p0-config>

2.10 jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!-- 引入jstl核心标签库 -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>分页查询数据</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
  <body>
  	<table border="1" width="80%" align="center" cellpadding="5" cellspacing="0">
  		<tr>
  			<td>序号</td>
  			<td>员工编号</td>
  			<td>员工姓名</td>
  		</tr>
  		<!-- 迭代数据 -->
  		<c:choose>
  			<c:when test="${not empty requestScope.pageBean.pageData}">
  			<!-- ${not empty requestScope.pageBean.pageData}
  			not empty:不为空
  			requestScope:使用El表达输出数据类型
  			 从四个域获取:${pageBean}
                              从指定域获取:	${pageScope.pageBean}
                             域范围: pageScoep / requestScope / sessionScope / applicationScope
  			
  			 -->
  				<c:forEach var="emp" items="${requestScope.pageBean.pageData}" varStatus="vs">
  					<tr>
  						<td>${vs.count }</td>
  						<td>${emp.empId }</td>
  						<td>${emp.empName }</td>
  					</tr>
  				</c:forEach>
  			</c:when>
  			<c:otherwise>
  				<tr>
  					<td colspan="3">对不起,没有你要找的数据</td>
  				</tr>
  			</c:otherwise>
  		</c:choose>
  		
  		<tr>
  			<td colspan="3" align="center">
  				当前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }页       
  				
  				<a href="${pageContext.request.contextPath }/index?currentPage=1">首页</a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage-1}">上一页 </a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage+1}">下一页 </a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.totalPage}">末页</a>
  			</td>
  		</tr>
  		
  	</table>
  </body>
</html>

2.11数据库

/*建库代码*/
CREATE DATABASE demo01 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
/*建表代码*/
CREATE TABLE dept( /*主表*/
deptid INT PRIMARY KEY AUTO_INCREMENT,
deptName VARCHAR(16) NOT NULL 
)

CREATE TABLE employee(/*从表*/
empId INT PRIMARY KEY AUTO_INCREMENT,
empName VARCHAR(16)  NOT NULL,
deptid  INT NOT NULL,
CONSTRAINT employee_dept_fk FOREIGN KEY(deptid) REFERENCES dept(deptid) ON UPDATE CASCADE ON DELETE CASCADE 
)

INSERT INTO dept(deptName) VALUES('开发部');
INSERT INTO dept(deptName) VALUES('销售部');
INSERT INTO dept(deptName) VALUES('后勤部');

INSERT INTO employee(empName,deptid) VALUES('张三',1)
INSERT INTO employee(empName,deptid) VALUES('李四',1)
INSERT INTO employee(empName,deptid) VALUES('王五',2)
INSERT INTO employee(empName,deptid) VALUES('刘六',2)
INSERT INTO employee(empName,deptid) VALUES('唐八',3)
INSERT INTO employee(empName,deptid) VALUES('吴七',3)

分页查询
起始行从0开始
分页:当前页  每页显示多少条
分页查询当前页的数据的sql: SELECT * FROM student LIMIT (当前页-1)*每页显示多少条,每页显示多少条
第一页两条数据
SELECT * FROM employee LIMIT 0,2