一.分页主要在于数据库查询,数据库主要要查两个
1.查询数据
2.查询数据条数,在除每页的条数,返回页数
dao包的操作:
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
//分页查询
int ts=5;
public List<XW> c(String a,int ys){
// int ys=1;
int kt=1+((ys-1)*ts);
int jw=ys*ts;
List<XW> list=new ArrayList<>();
try {
con=DBHelper.getcon();
ps=con.prepareStatement("select*from("
+ " select a.*,rownum from a3 a where Aname like ? "
+ ")b where rownum between ? and ?");
ps.setString(1,"%"+ a+"%");
ps.setInt(2, kt);
ps.setInt(3, jw);
rs=ps.executeQuery();
while(rs.next()) {
XW xw=new XW();
xw.setId(rs.getInt(1));
xw.setName(rs.getString(2));
xw.setNr(rs.getString(3));
list.add(xw);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.close(con, ps, rs);
}
return list;
}
//查条数,返回页数
public int c1(String a) {
int count=0;
try {
con=DBHelper.getcon();
ps=con.prepareStatement("select count(Aid) from a3 where Aname like ?");
ps.setString(1, "%"+a+"%");
rs=ps.executeQuery();
if(rs.next()) {
count= rs.getInt(1);//拿到条数,拿rs第一列
}
return (int)Math.ceil(count/ts);//向上取整,强转为int
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.close(con, ps, rs);
}
return 1;
}
1.select*from(
select a.*,rownum from a3 a where Aname like '%%'
)b where rownum between 1 and 5
rownum(伪列x.*,rownum) 伪列变实列
2.(int)Math.ceil(count/ts);//向上取整,强转为int
二.页面操作
<%
String newName = request.getParameter("newName");
//设定 当前用户进行分页的名字叫做page
String index = request.getParameter("page");
int n=1;//默认页数第一页
if(index!=null){
n=Integer.parseInt(index);//设置为你携带的页数
}
request.setCharacterEncoding("utf-8");
//查询当前数据的对应页数
int maxPage = new Dao().c1(newName);
//根据页数查询数据,遍历
for (News news : new Dao().c(newName,n)) {
%>
<!--将数据赋值到页面-->
<a href="${pageContext.request.contextPath}/news/read.jsp?newId=<%=news.getNewsId()%>"
data-placement="bottom" data-toggle="tooltip" href="" title="<%=news.getNewsTitle()%>">
<%=news.getNewsTitle()%>
</a>
}
<!--page=<%=Math.max(n - 1, 1)%>判断给的页数少于1为第一页-->
<a href="index.jsp?page=<%=Math.max(n - 1, 1)%>&newName=<%=newName%>"><span>«</span></a>
</li>
<%
//根据最大的页码 动态生成
for(int i=1;i<=maxPage;i++){
%>
<li class="<%=i==n?"active":""%>"><a href="index.jsp?page=<%=i%>&newName=<%=newName%>"><%=i%></a></li>
<%
}
%>
<li>
<!--判断大于最大页为最大页-->
<a href="index.jsp?page=<%=Math.min(n+1,maxPage)%>&newName=<%=newName%>"><span>»</span></a>
有几个非常值得注意的点:
1.page=<%=Math.max(n - 1, 1)%>往前一页n减一,总是拿最大值,n不会减到负数
2.class="<%=i==n?"active":""%>"当前页数是被选中的页数是给它添加active样式,当前页数的按钮颜色加深,更好确定处在哪个页数的页面