javabean servlet jsp实现分页功能代码解析

时间:2022-09-23 14:45:54

前端实现用ligerUI实现分页,感觉用框架确实简单,闲着无聊,模拟着liger的分页界面实现了一遍(只要是功能,样式什么无视) 

这里用基础的三层架构+servlet+jsp实现,思路很简单,把所有分页相关信息写入到一个pagebean类里面,service返回这个bean类,每次分页查询时都从该bean里查找信息。只是其中的细节问题比较繁琐,如边界处理(前端和后台边界都要处理),下拉框跳转后要显示当前页等等 

这是ligerUI实现的分页样式

javabean servlet jsp实现分页功能代码解析

模拟实现过程: 

目录结构

javabean servlet jsp实现分页功能代码解析

数据库(mysql)

javabean servlet jsp实现分页功能代码解析

model层,一个数据库对应的model(Blog),还有一个pageBean(BlogPage) 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.sql.Date;
 
public class Blog {
 private int id;
 private int category_id;
 private String title;
 private String content;
 private Date created_time;
  //getter和setter方法
 @Override
 public String toString() {
  return "Blog [id=" + id + ", category_id=" + category_id + ", id="codetool">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class BlogPage {
 private List<Blog> pagerecord;//每页记录
 private int pageno;//当前页
 private int pagenostart;//每页开始索引
 private int pagesize=5;//每页多少数据
 private int totalrecord;//总记录数
 private int totalpage;//总页数
 
 public BlogPage(int pageno,int totalrecord){
  //pageno totalrecord都可以当做已有信息
  this.totalrecord=totalrecord;
  //计算总页数
  totalpage=(totalrecord%pagesize==0)?totalrecord/pagesize:totalrecord/pagesize+1;
  //pageno的边界处理
  if(pageno<=1)
   this.pageno=1;
  else if(pageno>=totalpage)
   this.pageno=totalpage;
  else
   this.pageno=pageno;
  //计算每页开始索引,即每页第一个数据的索引,用于分页查询
  pagenostart=(this.pageno-1)*pagesize;
 }
 public int getPagenostart() {
  return pagenostart;
 }
 public void setPagenostart(int pagenostart) {
  this.pagenostart = pagenostart;
 }
 public List<Blog> getPagerecord() {
  return pagerecord;
 }
 public void setPagerecord(List<Blog> pagerecord) {
  this.pagerecord = pagerecord;
 }
 public int getPageno() {
  return pageno;
 }
 public void setPageno(int pageno) {
  this.pageno = pageno;
 }
 public int getPagesize() {
  return pagesize;
 }
 public void setPagesize(int pagesize) {
  this.pagesize = pagesize;
 }
 public int getTotalrecord() {
  return totalrecord;
 }
 public void setTotalrecord(int totalrecord) {
  this.totalrecord = totalrecord;
 }
 public int getTotalpage() {
  return totalpage;
 }
 public void setTotalpage(int totalpage) {
  this.totalpage = totalpage;
 }
}
 

dao层

JDBCUtil封装了jdbc的连接和释放操作

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class JDBCUtil {
 private static String url = "jdbc:mysql://localhost:3306/blogs_stu";
 private static String username = "root";
 private static String password = "";
 static {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public static Connection getConnection(){
  Connection conn;
  try {
   conn= DriverManager.getConnection(url, username, password);
   return conn;
  } catch (SQLException e) {
   e.printStackTrace();
 
  }
  return null;
 }
 public static void release(ResultSet rs,PreparedStatement ps,Connection conn){
  if(rs!=null){
   try {
    rs.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  if(ps!=null){
   try {
    ps.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  if(conn!=null){
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class BlogDao {
 //每页的记录,传入每页开始索引和每页大小用于分页,即limit的两个参数(mysql分页用limit)
 public List<Blog> getPageRecord(int pagenostart, int pagesize) {
  Connection conn = JDBCUtil.getConnection();
  PreparedStatement ps = null;
  ResultSet rs = null;
  String sql = "select * from blog limit ?,?";
  List<Blog> list = new ArrayList<Blog>();
  try {
   ps = conn.prepareStatement(sql);
   ps.setInt(1, pagenostart);
   ps.setInt(2, pagesize);
   rs = ps.executeQuery();
   while (rs.next()) {
    Blog blog = new Blog();
    blog.setId(rs.getInt("id"));
    blog.setCategory_id(rs.getInt("category_id"));
    blog.setTitle(rs.getString("title"));
    blog.setContent(rs.getString("content"));
    blog.setCreated_time(rs.getDate("created_time"));
    list.add(blog);
   }
   return list;
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   JDBCUtil.release(rs, ps, conn);
  }
  return null;
 }
 //总记录数
 public int getTotal() {
  Connection conn = JDBCUtil.getConnection();
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
   ps = conn.prepareStatement("select count(*) from blog");
   rs = ps.executeQuery();
   if (rs.next()) {
    return rs.getInt(1);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   JDBCUtil.release(rs, ps, conn);
  }
  return 0;
 }
}

service层

?
1
2
3
4
5
6
7
8
9
10
11
public class BlogService {
 BlogDao blogDao = new BlogDao();
 //返回pagebean,所有分页需要的信息都去pagebean里查找
 public BlogPage findPageRecord(int pageno) {
  int totalrecord = blogDao.getTotal();
  BlogPage blogpage = new BlogPage(pageno, totalrecord);
  List<Blog> list = blogDao.getPageRecord(blogpage.getPagenostart(),blogpage.getPagesize());
  blogpage.setPagerecord(list);
  return blogpage;
 }
}

servlet类 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@WebServlet("/BlogSplitServlet")
public class BlogSplitServlet extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html; charset=utf-8");
  String pagenostr=request.getParameter("pageno");
  //首次访问servletpagenostr为null,给一个初始值,即默认访问第一页
  int pageno=1;
  if(pagenostr!=null)
   pageno=Integer.parseInt(pagenostr);
  BlogService service=new BlogService();
  BlogPage blogPage=service.findPageRecord(pageno);
  request.setAttribute("blogPage", blogPage);
  request.getRequestDispatcher("/blogPage.jsp").forward(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }
}

这样所有的分页信息就封装到pagebean里了 

jsp实现只需要将pagebean里的信息取出来就行了 

下面给出我的jsp实现(模拟ligerUI) 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<%@page import="java.util.*,model.Blog,model.BlogPage"%>
<!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>Insert title here</title>
<script type="text/javascript">
 window.onload = function() {
  //保证select的option与当前页显示一致
  select = document.getElementById("select");
  pageno = '${blogPage.pageno}';
  select.options[pageno - 1].selected = 'selected';
 }
 //select下拉列表跳转
 function selectjump() {
  var pageno = select.selectedIndex + 1;
  window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno="
    + pageno;
 }
 //text跳转,onblur事件,输入框失去焦点是发生
 function textjump() {
  var pageno = document.getElementById("text").value;
  window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno="
    + pageno;
 }
</script>
</head>
<body>
 <%
  BlogPage blogPage = (BlogPage) request.getAttribute("blogPage");
  List<Blog> list = blogPage.getPagerecord();
  // 尾页填充空白行,若不填充,尾页表格tr行数与前面不一致很难看
  if (list.size() < blogPage.getPagesize()) {
   for (int i = list.size(); i < blogPage.getPagesize(); i++)
    list.add(null);
  }
 %>
 <div style="width: 50%; height: 400px">
  <table border="1" cellspacing="0" width="100%" bgcolor="#CEF0C5">
   <tr height="40px">
    <td>id</td><td>标题</td><td>内容</td><td>创建时间</td>
   </tr>
   <%
    for (Blog blog : list) {
     if (blog != null) {
   %>
   <tr height="50px">
    <td width="10%"><%=blog.getId()%></td>
    <td width="20%"><%=blog.getTitle()%></td>
    <td width="40%"><%=blog.getContent()%></td>
    <td width="30%"><%=blog.getCreated_time()%></td>
   </tr>
   <!-- 尾页空白行填充 -->
   <%} else {%>
   <tr height="50px">
    <td width="10%"></td>
    <td width="20%"></td>
    <td width="40%"></td>
    <td width="30%"></td>
   </tr>
   <%}}%>
  </table>
  <div style="height:50px;background-color: #4B7DB3;line-height: 40px;">
  &nbsp;&nbsp;
  <!-- select下拉框 -->
  <select id="select">
   <%for (int i = 1; i <= blogPage.getTotalpage(); i++) {%>
   <option onclick="selectjump()"><%=i%></option>
   <%}%>
  </select>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=1">首页</a>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getPageno()-1<1?blogPage.getPageno():blogPage.getPageno()-1%>">上一页</a>&nbsp;&nbsp;
  <input type="text" id="text" size="1px" value="${blogPage.pageno}" onblur="textjump()">/${blogPage.totalpage}
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getPageno()+1>blogPage.getTotalpage()?blogPage.getPageno():blogPage.getPageno()+1%>">下一页</a>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getTotalpage()%>">尾页</a>
  <div style="float: right;">
  显示从${blogPage.pagenostart+1}到${blogPage.pageno==blogPage.totalpage?blogPage.totalrecord:blogPage.pagesize},
  共${blogPage.totalrecord}条. 每页显示${blogPage.pagesize}条
  </div>
  </div>
 </div>
</body>
</html>

这是最后的样子,样式粗略的调了下,功能跟ligerUI默认的分页一模一样 

将JSP中代码改为标签(JSTL,需引入相应的jar包)并将JSP中的尾页补白放在servlet中后 

servlet中加入 

 

?
1
2
3
4
5
6
7
// 尾页填充空白行,若不填充,尾页表格tr行数与前面不一致很难看
  List<Blog> list = blogPage.getPagerecord();
  if (list.size() < blogPage.getPagesize()) {
   for (int i = list.size(); i < blogPage.getPagesize(); i++)
    list.add(null);
  }
  blogPage.setPagerecord(list);

jsp页面 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<%@page import="java.util.*,model.Blog,model.BlogPage"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript">
 //select下拉列表跳转
 function selectjump() {
  var select = document.getElementById("select");
  var pageno = select.selectedIndex + 1;
  window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno="
    + pageno;
 }
 //text跳转,onblur事件,输入框失去焦点时发生
 function textjump() {
  var pageno = document.getElementById("text").value;
  window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno="
    + pageno;
 }
</script>
</head>
<body>
 <div style="width: 50%; height: 400px">
  <table border="1" cellspacing="0" width="100%" bgcolor="#CEF0C5">
   <tr height="40px">
    <td>id</td><td>标题</td><td>内容</td><td>创建时间</td>
   </tr>
   <c:forEach items="${blogPage.pagerecord}" var="c" varStatus="vs">
   <c:if test="${c!=null}">
      <tr height="50px">
    <td width="10%">${c.id}</td>
    <td width="20%">${c.title}</td>
    <td width="40%">${c.content}</td>
    <td width="30%">${c.created_time}</td>
   </tr>
   </c:if>
   <!-- 尾页空白行填充 -->
   <c:if test="${c==null}">
   <tr height="50px">
    <td width="10%"></td>
    <td width="20%"></td>
    <td width="40%"></td>
    <td width="30%"></td>
   </tr>
   </c:if>
   </c:forEach>
  </table>
  <div style="height:50px;background-color: #4B7DB3;line-height: 40px;">
  &nbsp;&nbsp;
  <!-- select下拉框 -->
  <select id="select">
  <c:forEach begin="1" end="${blogPage.totalpage}" var="i">
  <option value="${i}" onclick="selectjump()" ${blogPage.pageno==i?'selected="selected"':''}>${i}</option>
  </c:forEach>
  </select>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=1">首页</a>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.pageno-1<1?blogPage.pageno:blogPage.pageno-1}">上一页</a>&nbsp;&nbsp;
  <input type="text" id="text" size="1px" value="${blogPage.pageno}" onblur="textjump()">/${blogPage.totalpage}
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.pageno+1>blogPage.totalpage?blogPage.pageno:blogPage.pageno+1}">下一页</a>
  <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.totalpage}">尾页</a>
  <div style="float: right;">
  显示从${blogPage.pagenostart+1}到${blogPage.pageno==blogPage.totalpage?blogPage.totalrecord:blogPage.pagesize},
  共${blogPage.totalrecord}条. 每页显示${blogPage.pagesize}条
  </div>
  </div>
 </div>
</body>
</html>

 实际运用中可以根据需求编写jsp页面,但是后台代码基本是通用的 

javabean servlet jsp实现分页功能代码解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐