jsp和Java是Web開發中常用的技術,在分頁功能實現上也有著重要的應用。以下是一個基于jsp和Java實現分頁的代碼示例。
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,com.example.dao.*,com.example.dto.*"%>
<%@ page import="javax.naming.*,javax.sql.*,java.sql.*"%>
<%!
private DataSource dataSource = null;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/myDB");
} catch (NamingException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public List<Book> getBooks(int page, int size) throws SQLException {
List<Book> list = new ArrayList<>();
try (
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement("select * from Book limit ?, ?");
) {
statement.setInt(1, (page - 1) * size);
statement.setInt(2, size);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setName(resultSet.getString("name"));
book.setPrice(resultSet.getDouble("price"));
list.add(book);
}
}
}
return list;
}
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>JSP分頁查詢示例</title>
</head>
<body>
<h2>JSP分頁查詢示例</h2>
<c:set var="pageSize" value="10" />
<c:set var="page" value="${param.page ? param.page : 1}" />
<c:set var="books" value="${getBooks(page, pageSize)}" />
<table border="1">
<tr>
<th>ID</th>
<th>名稱</th>
<th>價格</th>
</tr>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.id}</td>
<td>${book.name}</td>
<td>${book.price}</td>
</tr>
</c:forEach>
</table>
<c:set var="count" value="${fn:length(books)}" />
<c:if test="${count eq 0}">
當前頁無數據
</c:if>
<c:if test="${count eq pageSize}">
<a href="${page-1}.html">上一頁</a>
<a href="${page+1}.html">下一頁</a>
</c:if>
</body>
</html>