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>
摘自 宋利興的專欄