【前言】:分页技术是Javaweb中的常用技术。通常有两种方法实现,一是,利用结果集(ResultSet)来处理,即是先把所有的记录获取,然后在利用结果集的方法调用要使用的记录。用完后在关闭资源。二是采用sql语句处理。这样是即用即获取,利用sql语句的limit A B 语句查询指定项目。两种方式相比,前者比较耗费资源,所以一般采用第二种方法,具体用法如下。
【总】
这种方法可以使用典型的MVC结构实现。以下也是用这种模式进行分析。以下为实现商品信息的分页查询功能。运行效果如下:
一,M层(模型层)
包含两个Java文件:Product.java和ProductDao.java
1.完成的功能
A:封装商品信息,定义商品属性,即Product.java
B:封装商品对象的数据库相关操作,包括获取数据库连接独对象,查询一定条件的商品信息,查询总记录数(方便知道可以分成几页),即ProductDao.java
2.具体代码
A:Product.java
package com.lyq.bean;
/**
* 商品
* @author Li YongQiang
*
*/
public class Product {
public static final int PAGE_SIZE = 2;
// 编号
private int id;
// 名称
private String name;
// 价格
private double price;
// 数量
private int num;
// 单位
private String unit;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
B:ProductDao.java
package com.lyq.bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class BookDao {
/**
* 获取数据库连接
* @return Connection对象
*/
public Connection getConnection(){
// 数据库连接
Connection conn = null;
try {
// 加载数据库驱动,注册到驱动管理器
Class.forName("com.mysql.jdbc.Driver");
// 数据库连接字符串
String url = "jdbc:mysql://localhost:3306/db_database10";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "123456";
// 创建Connection连接
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回数据库连接
return conn;
}
/**
* 分页查询所有商品信息
* @param page 页数
* @return List<Product>
*/
public List<Product> find(int page){
// 创建List
List<Product> list = new ArrayList<Product>();
// 获取数据库连接
Connection conn = getConnection();
// 分页查询的SQL语句
String sql = "select * from tb_product order by id asc limit ?,?";
try {
// 获取PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
// 对SQL语句中的第1个参数赋值
ps.setInt(1, (page - 1) * Product.PAGE_SIZE);
// 对SQL语句中的第2个参数赋值
ps.setInt(2, Product.PAGE_SIZE);
// 执行查询操作
ResultSet rs = ps.executeQuery();
// 光标向后移动,并判断是否有效
while(rs.next()){
// 实例化Product
Product p = new Product();
// 对id属性赋值
p.setId(rs.getInt("id"));
// 对name属性赋值
p.setName(rs.getString("name"));
// 对num属性赋值
p.setNum(rs.getInt("num"));
// 对price属性赋值
p.setPrice(rs.getDouble("price"));
// 对unit属性赋值
p.setUnit(rs.getString("unit"));
// 将Product添加到List集合中
list.add(p);
}
// 关闭ResultSet
rs.close();
// 关闭PreparedStatement
ps.close();
// 关闭Connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 查询总记录数
* @return 总记录数
*/
public int findCount(){
// 总记录数
int count = 0;
// 获取数据库连接
Connection conn = getConnection();
// 查询总记录数SQL语句
String sql = "select count(*) from tb_product";
try {
// 创建Statement
Statement stmt = conn.createStatement();
// 查询并获取ResultSet
ResultSet rs = stmt.executeQuery(sql);
// 光标向后移动,并判断是否有效
if(rs.next()){
// 对总记录数赋值
count = rs.getInt(1);
}
// 关闭ResultSet
rs.close();
// 关闭Connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回总记录数
return count;
}
}
二、V层(视图层)
视图层就负责将获取的对象按照一定的规则显示出来就可以了。
三、C层(控制层)
1.完成的功能
A:首先,获取视图层传递来的信息,即需要获取那一页的信息,然后,使用M层的方法去获取相对应的记录并保存。
2.详细代码
package com.lyq.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 com.lyq.bean.BookDao;
import com.lyq.bean.Product;
/**
* Servlet implementation class FindServlet
*/
@WebServlet("/FindServlet")
public class FindServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FindServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 当前页码
int currPage = 1;//默认第一页
// 判断传递页码是否有效
if(request.getParameter("page") != null){
// 对当前页码赋值
currPage = Integer.parseInt(request.getParameter("page"));
}
// 实例化ProductDao
BookDao dao = new BookDao();
// 查询所有商品信息
List<Product> list = dao.find(currPage);
// 将list放置到request之中
request.setAttribute("list", list);
// 总页数
int pages ;
// 查询总记录数
int count = dao.findCount();
// 计算总页数
if(count % Product.PAGE_SIZE == 0){
// 对总页数赋值
pages = count / Product.PAGE_SIZE;
}else{
// 对总页数赋值
pages = count / Product.PAGE_SIZE + 1;
}
// 实例化StringBuffer
StringBuffer sb = new StringBuffer();
// 通过循环构建分页条
for(int i=1; i <= pages; i++){
// 判断是否为当前页
if(i == currPage){
// 构建分页条
sb.append("『" + i + "』");
}else{
// 构建分页条
sb.append("<a href='FindServlet?page=" + i + "'>" + i + "</a>");
}
// 构建分页条
sb.append(" ");
}
// 将分页条的字符串放置到request之中
request.setAttribute("bar", sb.toString());
// 转发到product_list.jsp页面
request.getRequestDispatcher("product_list.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
四、相关参数的说明
PAGE-SIZE:每页记录数【常量】----在sql语句中用
CurrPage:当前页,默认设置为“1”----在sql语句中用
Pages:总页数-----利用Cout,PAGE-SIZE求得
Cout:总记录数-----通过sql语句获得