MySQl + java-web 数据分页案例
本案例使用MySQl数据库,Servlet,jsp实现数据的分页功能。案例使用三层架构(持久层:操作数据库;服务层:业务处理;表现层:数据的接收,页面跳转等操作)表现层调用服务层,服务层调用持久层。步骤如下:
一、准备数据
-- 创建数据库
CREATE DATABASE db;
-- 使用数据库
USE db;
-- 创建数据表
CREATE TABLE dept(
deptno INT PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(20),
loc VARCHAR(30)
);
-- 添加数据
INSERT INTO dept(dname,loc) VALUES('测试','地址1');
INSERT INTO dept(dname,loc) VALUES('美工部','地址2');
INSERT INTO dept(dname,loc) VALUES('测试部','地址3');
INSERT INTO dept(dname,loc) VALUES('市场部','地址4');
INSERT INTO dept(dname,loc) VALUES('维护部','地址5');
INSERT INTO dept(dname,loc) VALUES('项目部','地址6');
INSERT INTO dept(dname,loc) VALUES('电竞部','地址7');
INSERT INTO dept(dname,loc) VALUES('套路部','地址8');
INSERT INTO dept(dname,loc) VALUES('分析部','地址9');
INSERT INTO dept(dname,loc) VALUES('加工部','地址10');
数据截图:
二、创建javaWeb项目
项目中需要导入的包如下:
jstl.jar和/standard.jar为jstl表达式jar包,mysql-connector-java-5.1.39-bin.jar 为mysql数据库驱动包
注:导入包之后记得将jar包加载到项目中,可以如图操作:选中包右键--》Build Path--》Add to Build Path
项目结构如下:
代码如下:
1、index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basepath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
MYSQl分页
部门编号
部门名称
部门地址
操作
无数据
${d.deptno }
${d.dname }
${d.loc }
修改
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
表现层
3、DeptServlet.java (使用注解的方式配置请求路径@WebServlet("/dept.do"))
package cn.sz.servlet;
import java.io.IOException;
import java.util.List;
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 cn.sz.pojo.Dept;
import cn.sz.service.DeptServiceImpl;
import cn.sz.service.IDeptService;
@WebServlet("/dept.do")
public class DeptServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置请求编码格式(防止中文乱码)
request.setCharacterEncoding("UTF-8");
// 设置响应编码格式(防止中文乱码)
response.setHeader("Content-Type", "text/html;charset=utf-8");/* 处理中文响应乱码 */
// 接收需要查看的页码
String cps = request.getParameter("cp");
// 接收每一页显示的数目
String pss = request.getParameter("ps");
int cp = 1;// 默认显示第一页
int ps = 5;// 默认每页显示5条
if (cps != null && !cps.equals("")) {
cp = Integer.parseInt(cps);
}
if (pss != null && !pss.equals("")) {
ps = Integer.parseInt(pss);
}
// 实例化Service层(调用Service层方法)
IDeptService iDeptService = new DeptServiceImpl();
// 查询总 的记录数
int counts = iDeptService.getCounts();
// 计算总是页数
int pageCounts = (counts - 1) / ps + 1;
// 查看要查看的页码的数据
List list = iDeptService.splitPage(cp, ps);
// 保存需要返回的数据
request.setAttribute("cp", cp);
request.setAttribute("ps", ps);
request.setAttribute("list", list);
request.setAttribute("counts", counts);
request.setAttribute("pageCounts", pageCounts);
// 转发到index.jsp页面
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
package cn.sz.dao;
import java.util.List;
import cn.sz.pojo.Dept;
public interface IDeptDAO {
/**
* 得到总的记录数
*
* @return
*/
int getCounts();
/**
* 查询每一个的记录
*
* @param pageNum
* 要查询的页码
* @param pageSize
* 每页显示的数目
* @return
*/
List splitPage(int pageNum, int pageSize);
}
package cn.sz.dao;
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 cn.sz.pojo.Dept;
import cn.sz.utils.DButils;
public class DeptDAOImpl implements IDeptDAO {
@Override
public int getCounts() {
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
try {
conn = DButils.getConn();
String sql = "SELECT COUNT(deptno) FROM dept";
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DButils.close(conn, psmt, rs);
}
return 0;
}
@Override
public List splitPage(int pageNum, int pageSize) {
List list = new ArrayList<>();
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
try {
conn = DButils.getConn();
String sql = "SELECT deptno,dname,loc FROM dept LIMIT ?,?";
psmt = conn.prepareStatement(sql);
psmt.setInt(1, (pageNum - 1) * pageSize);
psmt.setInt(2, pageSize);
rs = psmt.executeQuery();
while (rs.next()) {
Dept d = new Dept();
int deptno = rs.getInt(1);
String dname = rs.getString(2);
String loc = rs.getString(3);
d.setDeptno(deptno);
d.setDname(dname);
d.setLoc(loc);
list.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DButils.close(conn, psmt, rs);
}
return list;
}
}
package cn.sz.service;
import java.util.List;
import cn.sz.pojo.Dept;
public interface IDeptService {
/**
* 得到总的记录数
*
* @return
*/
int getCounts();
/**
* 查询每一个的记录
*
* @param pageNum
* 要查询的页码
* @param pageSize
* 每页显示的数目
* @return
*/
List splitPage(int pageNum, int pageSize);
}
package cn.sz.service;
import java.util.List;
import cn.sz.dao.DeptDAOImpl;
import cn.sz.dao.IDeptDAO;
import cn.sz.pojo.Dept;
public class DeptServiceImpl implements IDeptService {
private IDeptDAO iDeptDAO = new DeptDAOImpl();
@Override
public int getCounts() {
return iDeptDAO.getCounts();
}
@Override
public List splitPage(int pageNum, int pageSize) {
if (pageNum < 0 || pageSize < 0)
return null;
return iDeptDAO.splitPage(pageNum, pageSize);
}
}
package cn.sz.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
public class DButils {
/**
* 数据库的属性信息
*/
private static class DbProperties {
/** 数据库主机 IP地址 */
static final String IP = "localhost";
/** 数据库端口号 */
static final String PORT = "3306";
/** 数据库名 */
static final String DB_NAME = "db";
/** 数据库 URL */
static final String URL = "jdbc:mysql://" + IP + ":" + PORT + "/" + DB_NAME + "?charsetEncoding=utf-8";
// static final String URL =
// "jdbc:mysql://localhost:3306/db?charsetEncoding=utf-8";
/** 数据库连接用户名 */
static final String USER = "root";
/** 用户密码 */
static final String PSW = "";
}
// 获取数据库连接方法
public static Connection getConn() {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException e1) {
e1.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(DbProperties.URL, DbProperties.USER, DbProperties.PSW);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭数据库连接方法
public static void close(Connection conn, PreparedStatement psmt, ResultSet rs) {
// 关闭资源(先开的后关)
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (psmt != null)
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package cn.sz.pojo;
import java.io.Serializable;
public class Dept implements Serializable {
private Integer deptno;
private String dname;
private String loc;
public Dept() {
}
public Dept(Integer deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
}
}