自定义数据分页示例

来源:互联网 发布:mac的应用程序在哪里 编辑:程序博客网 时间:2024/05/16 12:41

JSP页面:

<%@ page language="java" import="java.util.*" 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+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</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">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
 
  <body>
    <div style="margin:0px auto; width:700px">
   <div id="title">
     <h3>自定义数据分页示例</h3><hr/>
   </div>
   <div id="data">
  <table border="1" width="600px" align="center">
   <thead>
     <th>序号</th>
     <th>名字</th>
   </thead>
   <tbody>
   <c:forEach items="${entities}" var="entity">
     <tr>
    <td>${entity.id}</td>
    <td>${entity.name}</td>
     </tr>
   </c:forEach>
   </tbody>
  </table>
   </div>
   <div id="a">
     <a href="${pageContext.request.contextPath}/data?pages=1">首页</a>
     <a href="${pageContext.request.contextPath}/data?pages=${pages-1<=1?1:pages-1}">上一页</a>
     <a href="${pageContext.request.contextPath}/data?pages=${pages+1>sumpages?sumpages:pages+1}">下一页</a>
     <a href="${pageContext.request.contextPath}/data?pages=${sumpages}">末页</a>共${sum}条
   </div>
  </body>
</html>

Java类:

domain层:Customer类

package cn.csdn.customer.domain;

import java.io.Serializable;
import java.sql.Date;


public class Customer implements Serializable{
 
 private static final long serialVersionUID = 1L;
 
 /*编号*/
 private int id;
 /*客户姓名*/
 private String name;
 /*性名*/
 private String gender;
 /*生日*/
 private Date birthday;
 /*手机*/
 private String cellphone;
 /*电子邮箱*/
 private String Email;
 /*客户爱好*/
 private String perference;
 /*客户类型*/
 private String type;
 /*备注*/
 private String Description;
 
 /*默认构造器*/
 public Customer() {
  super();
 }
 /*有参构造器*/
 public Customer(String name, String gender, Date birthday,
   String cellphone, String email, String perference, String type,
   String description) {
  super();
  this.name = name;
  this.gender = gender;
  this.birthday = birthday;
  this.cellphone = cellphone;
  Email = email;
  this.perference = perference;
  this.type = type;
  Description = description;
 }

 /*set和get方法*/
 
 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 String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

 public Date getBirthday() {
  return birthday;
 }

 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }

 public String getCellphone() {
  return cellphone;
 }

 public void setCellphone(String cellphone) {
  this.cellphone = cellphone;
 }

 public String getEmail() {
  return Email;
 }

 public void setEmail(String email) {
  Email = email;
 }

 public String getPerference() {
  return perference;
 }

 public void setPerference(String perference) {
  this.perference = perference;
 }

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 public String getDescription() {
  return Description;
 }

 public void setDescription(String description) {
  Description = description;
 }

 @Override
 public String toString() {
  return "Customer [id=" + id + ", name=" + name + ", gender=" + gender
    + ", birthday=" + birthday + ", cellphone=" + cellphone
    + ", Email=" + Email + ", perference=" + perference + ", type="
    + type + ", Description=" + Description + "]";
 }
 
 
}

dao层:

Dao接口:

package cn.csdn.customer.dao;

import java.util.List;

public interface Dao<T,PK> {
 
 /*插入实体*/
 boolean insert(T entity);
 
 /*更新实体*/
 boolean update(T entity);
 
 /*删除实体*/
 boolean delete(T entity);
 
 /*查询所有实体*/
 List<T> findAll(PK start,PK count);
 
 /*根据主键查询实体*/
 T findById(PK id);
 
}

CustomerDao接口:

package cn.csdn.customer.dao;

import cn.csdn.customer.domain.Customer;

public interface CustomerDao extends Dao<Customer,Integer> {
  int getCount();
}

CustomerDaoImpl接口实例类:

package cn.csdn.customer.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.csdn.customer.domain.Customer;
import cn.csdn.customer.util.JdbcUtil;

public class CustomerDaoImpl implements CustomerDao {
 
 /* 封装数据库操作的对象 */
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 
 public boolean insert(Customer entity) {
  /* 第一步:声明返回值变量 */
  boolean flag = false;
  try {
   /* 第二步:获取连接对象 */
   conn = JdbcUtil.getConn();
   /* 第三步:定义sql语句 */
   String sql = "insert into customer(name,gender,birthday,cellphone,Email,preference,type,Description)values(?,?,?,?,?,?,?,?)";
   /* 第四步:根据sql语句获取预处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为占位符赋值 */
   int index = 1;
   pstmt.setObject(index++, entity.getName());
   pstmt.setObject(index++, entity.getGender());
   pstmt.setObject(index++, entity.getBirthday());
   pstmt.setObject(index++, entity.getCellphone());
   pstmt.setObject(index++, entity.getEmail());
   pstmt.setObject(index++, entity.getPerference());
   pstmt.setObject(index++, entity.getType());
   pstmt.setObject(index++, entity.getDescription());
   /* 第六步:执行更新 */
   int i = pstmt.executeUpdate();
   /* 第七步:判断 */
   if (i > 0) {
    flag = true;
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  /* 第八步:释放资源 */
  JdbcUtil.release(rs, pstmt, conn);
  /* 必须修改返回值的变量 */
  return flag;
 }

 public boolean update(Customer entity) {
  /* 第一步:声明返值的变量 */
  boolean flag = false;
  /* 第二步:获取连接对象 */
  try {
   conn = JdbcUtil.getConn();
   /* 第三步:获取连接对象 */
   //name,gender,birthday,cellphone,Email,preference,type,Description
   String sql = "update customer set name=?,gender=?,birthday=?,cellphone=?,Email=?,preference=?,type=?,Description=?,where id=?";
   /* 第四步:根据sql语句获取与处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为占位符赋值 */
   int index = 1;
   pstmt.setObject(index++, entity.getName());
   pstmt.setObject(index++,entity.getGender());
   pstmt.setObject(index++, entity.getBirthday());
   pstmt.setObject(index++, entity.getCellphone());
   pstmt.setObject(index++, entity.getEmail());
   pstmt.setObject(index++, entity.getPerference());
   pstmt.setObject(index++, entity.getType());
   pstmt.setObject(index++, entity.getDescription());
   pstmt.setObject(index++, entity.getId());
   /* 第六步:执行更新 */
   int i = pstmt.executeUpdate();
   /* 第七步:判断 */
   if (i > 0) {
    flag = true;
   }
   /* 第八步:释放资源 */
   JdbcUtil.release(rs, pstmt, conn);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return flag;
 }

 public boolean delete(Customer entity) {
  /* 第一步:声明返回变量 */
  boolean flag = false;
  try {
   /* 第二步:获取连接对象 */
   conn = JdbcUtil.getConn();
   /* 关闭 */
   conn.setAutoCommit(false);
   /* 第三步:定义sql语句 */
   String sql = "delete from customer where id=?";
   /* 第四步:根据sql语句创建与处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为站位赋值 */
   int index = 1;
   pstmt.setObject(index++,entity.getId());
   /* 第六步:执行更行 */
   int i = pstmt.executeUpdate();
   /* 第七步:判断 */
   if (i > 0) {
    flag = true;
   }
   conn.commit();
  } catch (Exception e) {
   try {
    conn.rollback();
   } catch (SQLException e1) {
    e1.printStackTrace();
   }
   e.printStackTrace();
  } finally {
   try {
    conn.setAutoCommit(true);
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  /* 第八步:释放资 */
  JdbcUtil.release(rs, pstmt, conn);
  return flag;
 }

 public List<Customer> findAll(Integer start,Integer count) {
  /* 第一步:声明返回值变量 */
  List<Customer> entities = new ArrayList<Customer>();
  try {
   /* 第二步:获取连接对象 */
   conn = JdbcUtil.getConn();
   /* 第三步:定义sql语句 */
   String sql = "select id,name,gender,birthday,cellphone,Email,preference,type,Description from customer limit ?,? ";
   /* 第四步:根据sql语句获取与处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为占位符赋值 */
   int index = 1;
   pstmt.setObject(index++,start);
   pstmt.setObject(index++,count);
   /* 第六步:执行查询操作 */
   rs = pstmt.executeQuery();
   /* 第七步:判断 */
   while(rs.next()) {
    Customer entity=new Customer();
    // 把记录中的字段赋值给实体的相应属性
    entity.setId(rs.getInt("id"));
    entity.setName(rs.getString("name"));
    entity.setGender(rs.getString("gender"));
    entity.setBirthday(rs.getDate("birthday"));
    entity.setCellphone(rs.getString("cellphone"));
    entity.setEmail(rs.getString("Email"));
    entity.setPerference(rs.getString("preference"));
    entity.setType(rs.getString("type"));
    entity.setDescription(rs.getString("Description"));
    entities.add(entity);
   }
   /* 第八步:释放资源 */
   JdbcUtil.release(rs, pstmt, conn);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return entities;
 }

 public Customer findById(Integer id) {
  /* 第一步:声明返回值变量 */
  Customer entity = new Customer();
  try {
   /* 第二步:获取连接对象 */
   conn = JdbcUtil.getConn();
   /* 第三步:定义sql语句 */
   String sql = "select id,name,gender,birthday,cellphone,Email,preference,type,Description from customer where id=?";
   /* 第四步:根据sql语句获取与处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为占位符赋值 */
   int index = 1;
   pstmt.setObject(index++,id);
   /* 第六步:执行查询操作 */
   rs = pstmt.executeQuery();
   /* 第七步:判断 */
   if (rs.next()) {
    // 把记录中的字段赋值给实体的相应属性
    entity.setId(rs.getInt("id"));
    entity.setName(rs.getString("name"));
    entity.setGender(rs.getString("gender"));
    entity.setBirthday(rs.getDate("birthday"));
    entity.setCellphone(rs.getString("cellphone"));
    entity.setEmail(rs.getString("Email"));
    entity.setPerference(rs.getString("preference"));
    entity.setType(rs.getString("type"));
    entity.setDescription(rs.getString("Description"));
   }
   /* 第八步:释放资源 */
   JdbcUtil.release(rs, pstmt, conn);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return entity;
 }

 public int getCount() {
  /* 第一步:声明返回值变量 */
  int count=0;
  try {
   /* 第二步:获取连接对象 */
   conn = JdbcUtil.getConn();
   /* 第三步:定义sql语句 */
   String sql = "select count(*) as s from customer";
   /* 第四步:根据sql语句获取与处理对象 */
   pstmt = conn.prepareStatement(sql);
   /* 第五步:为占位符赋值 */
   /* 第六步:执行查询操作 */
   rs = pstmt.executeQuery();
   /* 第七步:判断 */
   if(rs.next()){
    count=rs.getInt("s");
   }
   /* 第八步:释放资源 */
   JdbcUtil.release(rs, pstmt, conn);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return count;
 }
}

Servlet层:DataServlet

package cn.csdn.customer.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.csdn.customer.dao.CustomerDao;
import cn.csdn.customer.dao.CustomerDaoImpl;
import cn.csdn.customer.domain.Customer;

public class DataServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;
 
 private CustomerDao customerDao = new CustomerDaoImpl();
 final static int count = 10;


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

 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
   /* 获取要显示当前页参数 */
   int pages=Integer.parseInt(request.getParameter("pages"));
   /* 查寻数据的起始点 */
   int start =(pages-1)* count;
   /* 查询要显示的数据 */
   List<Customer> entities = customerDao.findAll(start,count);
   /* 查询数据的条数 */
   int sum=customerDao.getCount();
   /* 查询数据的条数 */
   int sumpages=(sum/count==0?sum/count:sum/count+1);
   request.setAttribute("pages",pages);
   request.setAttribute("entities", entities);
   request.setAttribute("sum",sum);
   request.setAttribute("sumpages",sumpages);
   // 转发
   request.getRequestDispatcher("./index.jsp").forward(request,response);
 }

}

 

Juitl工具:JdbcUtil

package cn.csdn.customer.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import java.sql.PreparedStatement;


public class JdbcUtil {
 /* 声明dataSource对象 */
 private static DataSource dataSource;
 static {
  try {
   Properties properties = new Properties();
   // 加载驱动
   InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("config/dbcp.properties");
   //从流中读取属性列表
   properties.load(is);
   dataSource = BasicDataSourceFactory.createDataSource(properties);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 /*获取连接对象*/
 public static Connection getConn() throws SQLException{
  
  return dataSource.getConnection();
 }
 /*释放资源*/
 public static void release(ResultSet rs,PreparedStatement pstmt,Connection conn){
  
  if(rs!=null){
   try {
    rs.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if(pstmt!=null){
   try {
    pstmt.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if(conn!=null){
   try {
    conn.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 public static void main(String[] args) throws SQLException {
    new JdbcUtil();
   System.out.println(dataSource.getConnection());
 }
}

 

XML描述文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>DataServlet</servlet-name>
    <servlet-class>cn.csdn.customer.servlet.DataServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>DataServlet</servlet-name>
    <url-pattern>/data</url-pattern>
  </servlet-mapping> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>