版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)
1,新建一个项目,以BaseDao为例(JDBC封装),封装分页方法。
2,引入数据库连接jar包。
3,引入basedao封装代码。
4,编写jsp代码。
其中%内容%这样的形式是在jsp里面编写java代码的格式,在jsp顶部引入c标签库。
jsp代码如下:
<%@page import="com.aaa.util.BaseDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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>
<% String stuPageNo=request.getParameter("pageNo");
int pageNo=0;
if(stuPageNo==null){
pageNo=1;
}else{
pageNo=Integer.valueOf(stuPageNo);
}
if(pageNo<1){
pageNo=1;
}
int totalCount=0;
List<Map<String,Object>> count=BaseDao.selectMap("select count(*) as cou from student", null);
if(count!=null&&count.size()>0){
totalCount=Integer.valueOf(count.get(0).get("cou")+"");
}
int pageSize=5;
int maxPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
if(pageNo>maxPage){
pageNo=maxPage;
}
List<Map<String,Object>> stuList=BaseDao.selectMap("select id,name,address,sex from student limit "+(pageNo-1)*pageSize+","+pageSize, null);
request.setAttribute("stuList", stuList);
request.setAttribute("pageNo", pageNo);
request.setAttribute("totalCount", totalCount);
request.setAttribute("maxPage", maxPage);
%>
<table border="1" width="400px">
<tr align="center">
<th>ID</th>
<th>姓名</th>
<th>地址</th>
<th>性别</th>
</tr>
<c:forEach items="${stuList}" var="stu">
<tr align="center">
<td>${stu.id }</td>
<td>${stu.name }</td>
<td>${stu.address }</td>
<td>${stu.sex }</td>
</tr>
</c:forEach>
<tr>
<td colspan="4">
<a href="index.jsp?pageNo=1">首页</a>
<a href="index.jsp?pageNo=${pageNo-1 }">上一页</a>
<a href="index.jsp?pageNo=${pageNo+1 }">下一页</a>
<a href="index.jsp?pageNo=${maxPage }">尾页</a>
跳转到<select onchange="togo(this.value)">
<c:forEach var="page" begin="1" end="${maxPage}">
<c:choose>
<c:when test="${page==pageNo}">
<option selected="selected" value="${page }">${page }</option>
</c:when>
<c:otherwise>
<option value="${page }">${page }</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>页
共${totalCount }条${maxPage}页
</td>
</tr>
</table>
<script type="text/javascript">
function togo(v){
location.href="index.jsp?pageNo="+v;
}
</script>
</body>
</html>
5,启动tomcat,输入localhost:8080/项目名/index.jsp访问,会出现如下分页查询结果。
以上是最基本的思路,可以把jsp中的java脚本写一个类封装起来,把pageNo和sql语句作为参数传到那个类里边,得到所有的属性值之后保存到request域中,最后转发到index.jsp页面即可。