booklist.jsp

<%@page import="books.accp.utils.Pager"%>
<%@page import="books.accp.entities.Book"%>
<%@page import="java.util.List"%>
<%@page import="books.accp.bizImpl.BooksMangerImpl"%>
<%@page import="books.accp.biz.BooksManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    BooksManager manager = new BooksMangerImpl();
    int pageindex = 1;
    if (request.getParameter("pageindex") != null)
        pageindex = Integer.parseInt(request.getParameter("pageindex"));
    Pager pager = new Pager();
    pager.setTotalCount(manager.GetBookCount());
    pager.setPageSize(3);
    pager.setPageIndex(pageindex);
    pager.getPageCount();

    List<Book> list = manager.GetBookListByPage(pager);
    request.setAttribute("list", list);
    request.setAttribute("pager", pager);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>书籍列表</title>
</head>
<body>
    <table>
        <tr>
            <th>编号</th>
            <th>书名</th>
            <th>价格</th>
            <th>图片</th>
            <th>库存</th>
        </tr>
        <c:forEach var="book" items="${list}">
            <tr>
                <td>${book.bid }</td>
                <td><a href="bookinfo.aspx?bid=${book.bid}">${book.bookName }</a></td>
                <td>${book.b_price }</td>
                <td><img src="${image}" /></td>
                <td>${book.stock }</td>
            </tr>
        </c:forEach>
    </table>
     <%@ include file="../utils/pager.jsp"%>
<%--     <jsp:include page="../utils/pager.jsp"></jsp:include> --%>
</body>
</html>

 

抽取出来的pager.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<style type="text/css">
.txtgo {
    width: 30px;
    border: 1px solid;
}
</style>

<script type="text/javascript">
    function goPage(pageindex) {        
        document.getElementById("pageindex").value = pageindex;
        document.forms[0].submit();
    }
    
    function jumpTo(){
        var pageindex = document.getElementById("pageindex").value;
         var regexp=/^\d+$/;
        if(!regexp.test(pageindex)){
            alert("请输入正确的数字!");
            return false;
        }else{
            goPage(pageindex);
        }          
    }
</script>
<form name="frmpage" method="post">
    <div id="pager">
        <c:if test="${pager.pageIndex > 1 }">
            <a href="#" onclick="goPage(1)">首页</a>
            <a href="#" onclick="goPage(${ pager.pageIndex - 1 })">上一页</a>
        </c:if>
        <c:if test="${pager.pageIndex < pager.pageCount }">
            <a href="#" onclick="goPage(${ pager.pageIndex + 1 })">下一页</a>
            <a href="#" onclick="goPage(${ pager.pageCount})">末页</a>
        </c:if>
        <input type="text" id="pageindex" name="pageindex"
            value="${param.pageindex == null ? 1 : param.pageindex}"
            class="txtgo" /> <input type="button" value="go" onclick="jumpTo()">
    </div>
</form>

 

公共分页类:pager.java

package books.accp.utils;

public class Pager {

    //当前页
    private int pageIndex = 1;
    //页大小
    private int pageSize = 3;
    //总记录数
    private int totalCount = 0;
    //总页数
    private int pageCount = 0;

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalCount() {
        return totalCount;
    }

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

    /**
     * 获取总页数
     * 
     * @return
     */
    public int getPageCount() {
        pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount
                / pageSize + 1;
        return pageCount;
    }

    /**
     * 获取开始记录数
     * 
     * @return
     */
    public int getStartRow() {
        return (pageIndex - 1) * pageSize + 1;
    }

    /**
     * 获取结束记录数
     * @return
     */
    public int getEndRow() {
        return pageIndex * pageSize;
    }

}

 

数据访问层:BookDaoImpl.java

package books.accp.daoImpl;

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

import books.accp.dao.BaseDao;
import books.accp.dao.BooksDao;
import books.accp.entities.Book;
import books.accp.utils.Pager;

public class BooksDaoImpl extends BaseDao implements BooksDao {

    @Override
    public List<Book> GetBookList() {
        String sql = "select * from Books";
        ResultSet rs = ExecuteQuery(sql, null);
        List<Book> list = GetResultSetToList(rs);
        return list;
    }

    @Override
    public int GetBookCount() {
        String sql = "select count(*) from Books";
        Object obj = ExecuteScanlar(sql, null);
        int count = obj == null ? 0 : Integer.parseInt(obj.toString());
        return count;
    }

    @Override
    public List<Book> GetBookListByPage(Pager pager) {
        String sql = "SELECT * FROM (SELECT Books.*,ROWNUM AS rn FROM Books) WHERE rn >= ? AND rn <= ?";
        Object[] paras = new Object[2];
        paras[0] = pager.getStartRow();
        paras[1] = pager.getEndRow();
        ResultSet rs = ExecuteQuery(sql, paras);
        List<Book> list = this.GetResultSetToList(rs);
        return list;
    }

    public List<Book> GetResultSetToList(ResultSet rs) {
        List<Book> list = new ArrayList<Book>();
        try {
            while (rs.next()) {
                Book b = new Book();
                b.setBid(rs.getInt("bid"));
                b.setBookName(rs.getString("bookname"));
                b.setB_price(rs.getDouble("B_price"));
                b.setImage(rs.getString("Image"));
                b.setStock(rs.getInt("Stock"));
                list.add(b);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CloseAll(rs);
        }
        return null;
    }
}

数据访问接口:BooksDao.java

package books.accp.dao;

import java.sql.ResultSet;
import java.util.List;

import books.accp.entities.Book;
import books.accp.utils.Pager;

public interface BooksDao{
    public List<Book> GetBookList();
    
    public int GetBookCount();
    
    public List<Book> GetResultSetToList(ResultSet rs);
    
    public List<Book> GetBookListByPage(Pager pager);
}

 

BaseDao.java

package books.accp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class BaseDao {
    private static String jdbcname = "java:comp/env/jdbc/books";
    private static Connection con;
    private static PreparedStatement stmt;

    /**
     * 关闭jdbc对象
     * 
     * @param rs
     */
    public static void CloseAll(ResultSet rs) {
        // 关闭操作对象
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建连接对象
     * 
     * @return
     */
    private static Connection CreateConnection() {
        // 通过连接池创建Connection对象,一定是基于Tomcat的应用,连接池是由Tomcat进行管理
        Context context;
        try {
            context = new InitialContext();
            DataSource ds = (DataSource) context.lookup(jdbcname);
            con = ds.getConnection();
            return con;
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 为PreparedStatement添加参数
     * 
     * @param stmt
     * @param paras
     */
    private static void AddPararents(PreparedStatement stmt, Object[] paras) {
        try {
            if (paras != null && paras.length > 0) {
                for (int i = 0; i < paras.length; i++) {
                    stmt.setObject(i + 1, paras[i]);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行查询的方法
     * 这里不能关闭ResultSet,因为是ResultSet是一个游标,必须保持数据库的打开状态
     * @param 要执行的sql语句
     * @param sql语句执行的参数
     * @return
     */
    public static ResultSet ExecuteQuery(String sql, Object[] paras) {
        ResultSet rs = null;
        try {
            con = CreateConnection();

            stmt = con.prepareStatement(sql);

            AddPararents(stmt, paras);
            // 执行查询操作,返回ResultSet对象
            rs = stmt.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回首行首列
     * 
     * @param sql
     * @param paras
     * @return
     */
    public static Object ExecuteScanlar(String sql, Object[] paras) {
        ResultSet rs = null;
        try {
            con = CreateConnection();
            stmt = con.prepareStatement(sql);
            AddPararents(stmt, paras);
            // 执行查询操作,返回ResultSet对象
            rs = stmt.executeQuery();
            if (rs != null && rs.next()) {
                return rs.getObject(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CloseAll(rs);
        }
        return null;
    }

    /**
     * 执行增加、修改、删除的方法
     * 
     * @param sql
     * @param paras
     * @return
     */
    public static int ExecuteUpdate(String sql, Object[] paras) {
        try {
            con = CreateConnection();
            stmt = con.prepareStatement(sql);
            AddPararents(stmt, paras);
            // 执行查询操作,返回ResultSet对象
            int result = stmt.executeUpdate();
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CloseAll(null);
        }
        return -1;
    }
}

 

连接池:

<Resource name="jdbc/books" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000" username="bookuser" password="bookuser"
        driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:localhost:1521:orcl" />

 

SQL表:

create table BOOKS
(
  BID      NUMBER not null,
  BOOKNAME VARCHAR2(100) not null,
  B_PRICE  VARCHAR2(10) not null,
  IMAGE    VARCHAR2(200) not null,
  STOCK    NUMBER not null
)
;
alter table BOOKS
  add constraint PK_BOOKID primary key (BID);

prompt Loading BOOKS...
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (27, '泰戈尔诗集', '18.00', 'images/book/book_01.gif', 979);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (28, '痕记', '22.80', 'images/book/book_02.gif', 977);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (29, '天堂之旅', '25.00', 'images/book/book_03.gif', 989);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (30, '钱钟书集', '332.50', 'images/book/book_04.gif', 999);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (31, '赵俪生高昭—夫妻回忆录', '38.00', 'images/book/book_05.gif', 998);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (32, '无聊斋', '28.00', 'images/book/book_06.gif', 998);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (33, '一颗热土豆是一张温馨的床', '38.00', 'images/book/book_07.gif', 999);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (34, '李戡戡乱记', '22.00', 'images/book/book_08.gif', 999);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (35, '生生世世未了缘', '17.50', 'images/book/book_09.gif', 999);
insert into BOOKS (BID, BOOKNAME, B_PRICE, IMAGE, STOCK)
values (36, '一生有多少爱', '17.50', 'images/book/book_10.gif', 999);

 

源代码

posted on 2015-05-31 15:50  Builder  阅读(408)  评论(0编辑  收藏  举报