悠悠楠杉
JSP实现分页效果,jsp实现分页效果的代码
1. 数据库准备
首先,你需要一个数据库表来存储文章信息。这里是一个简单的SQL示例:
sql
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
keywords TEXT,
description TEXT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. 创建JSP页面
2.1 显示文章列表和分页控制(listArticles.jsp
)
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Article List</title>
</head>
<body>
<h1>Article List</h1>
<%-- 假设每页显示5篇文章 --%>
<div class="pagination">
<a href="${page - 1 <= 0 ? 'javascript:void(0);' : 'page?page=' + (page - 1)}">上一页</a>
<a href="${page + 1 >= totalPages ? 'javascript:void(0);' : 'page?page=' + (page + 1)}">下一页</a>
</div>
<ul>
<% for (int i = (page - 1) * 5; i < Math.min(totalArticles, page * 5); i++) { %>
<li>
<h2><%= articles.get(i).getTitle() %></h2>
<p><%= articles.get(i).getDescription() %></p>
<a href="showArticle?id=<%= articles.get(i).getId() %>">Read More</a>
</li>
<% } %>
</ul>
</body>
</html>
注意:这里page
和totalPages
、totalArticles
及articles
列表应由相应的Servlet在服务器端设置和传递。实际实现中,需通过request.setAttribute
设置这些值。
2.2 显示单个文章(showArticle.jsp
)
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Article Detail</title>
</head>
<body>
<h1><%= article.getTitle() %></h1>
<p><strong>Keywords:</strong> <%= article.getKeywords() %></p>
<p><strong>Description:</strong></p>
<%= article.getDescription() %> <!-- 此处仅为示例,实际使用时可能需要更好的格式化 -->
<p><strong>Content:</strong></p> <!-- 仅展示部分内容 -->
<%= article.getContent().substring(0, 1000) %>... <!-- 截取前1000字 -->
</body>
</html>
3. Servlet处理逻辑(示例)
假设你有一个名为ArticleServlet
的Servlet来处理请求和传递数据到JSP页面。你需要编写一个方法来获取文章列表并计算分页信息:
java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = Integer.parseInt(request.getParameter("page")); // 分页参数,默认值为1或从请求中获取当前页码。 确保有合理的错误处理机制。
int totalArticles = // 从数据库获取文章总数; 示例代码中省略具体实现。
int articlesPerPage = 5; // 每页文章数,可配置。
int totalPages = (int) Math.ceil((double) totalArticles / articlesPerPage); // 计算总页数。 确保不小于1。 否则为第一页设置一个"首页"链接指向该页面。 例如:page=1。 反之亦然。}。"} >} >} >} >} >} >} >} >} >} >} >} >} >} >} >} >} >} >}});";// >>"}))};";// >>"}))};";// >>"}})); // 从数据库获取分页文章数据,存储在List中。注意数据库查询应包含排序,以保持分页一致性。请求属性传递到JSP页面:request.setAttribute("articles", articleList); request.setAttribute("page", page); request.setAttribute("totalPages", totalPages); request.getRequestDispatcher("/listArticles.jsp").forward(request, response); }