关键代码及其思路:
1.定义变量:
(1)pageCount 总共的页数(未知)
(2)pageSize 每页显示的记录数(已知)
(3)pageNow 希望显示的当前页(已知,一般赋值为1)
(4)rowCount 总共的记录数(未知)
2. 计算pageCount和rowCount
(1)求pageCount:
if(rowCount % pageSize == 0) {
pageCount = rowCount / pageSize;
}else {
pageCount = rowCount /pageSize + 1;
}
(2)求rowPage:
PreparedStatement ps = con.prepareStatement("select count(*) from users");
ResultSet rs = ps.executeQuery();
if(rs.next()) {
rowCount = rs.getInt(1);
}
3.java连接数据库
(1)加载JDBC Class.forName("com.mysql.jdbc.Driver");
(2)数据库连接 Connection con = DriverManager.getConnection("jdbc.mysql://localhost:3306/数据库名称","用户名","密码");
Connection con = DriverManager.getConnection("jdbc.mysql://localhost:3306/db_user","root","");
(3)用于执行sql语句 PreparedStatement ps = con.prepareStatement("sql语句");
应用实例:
i.PreparedStatement ps = con.prepareStatement("select count(*) from users");
ii.PreparedStatement ps = con.prepareStatement("select * from users limit ?,?");
给?赋值法:
ps.setInt(1,(pageNow-1)*pageSize);
ps.setInt(2,pageSize);
(4) ResultSet rs = ps.executeQuery();
4.html格式声明和处理中文乱码
res.setContentType("text/html;charset=utf8");
5.插入图片
PrintWriter pw = res.getWriter();
pw.println("<img height=100px width=100px src=imgs/KSYoon.jpg>");
6.分页链接
(1)页数链接(将所有的页数都显示输出)
for(int i=1;i<=pageCount;i++) {
pw.println("<a href=wel3?pageCur="+i+">"+i+"</a>");
}
注意点:当页数过多时,显示的页数过于冗长,为了改善这一缺点,采取显示部分页数的方法
for(int i=pageNow;i<pageNow+10;i++) {
pw.println("<a href=wel3?pageCur="+i+">"+i+"</a>");
}
(2)上一页链接(点击后当前页数加1)
if(pageNow!=1) {
pw.println("<a href=wel3?pageCur="+(pageNow-1)+">上一页</a>");
}
(3)下一页链接(点击后当前页数减1)
if(pageNow!=pageCount) {
pw.println("<a href=wel3?pageCur="+(pageNow+1)+">下一页</a>");
}
7.动态接收pageCur(重点)
String sPageNow = req.getParameter("pageCur");
if(sPageNow!=null) {
pageNow = Integer.parseInt(sPageNow);
}