简单的web网页分页

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="javax.naming.*" import="javax.sql.DataSource"
 import="java.sql.*;"%>
<%
 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>
 <%!//总页数
 int totalPageCount = 1;
 //每页显示的数量
 int pageSize = 5;
 //当前页码
 int totalpageCount = 0;

 int totalCount = 0;

 Connection conn = null;
 PreparedStatement pstmt = null;
 ResultSet rs = null;

 void select() {

  try {
   pstmt = conn.prepareStatement("select count(1) from topic");
   rs = pstmt.executeQuery();
   while (rs.next()) {
    totalCount = rs.getInt(1);
   }

  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   totalpageCount = totalCount % pageSize == 0 ? (totalCount / pageSize)
     : (totalCount / pageSize + 1);

  }
 }%>

 <%
 if (null != request.getParameter("opr")) {
  totalPageCount = Integer.parseInt(request
    .getParameter("opr"));
 }
  int pageindex = 0;
  Connection conn = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  Context ctx = new InitialContext();
  DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/news");
  conn = ds.getConnection();
  try {

   ps = conn.prepareStatement("select tname from topic LIMIT ?,?");
   
   ps.setInt(1, (totalPageCount-1) * pageSize);
   ps.setInt(2, pageSize);
   rs = ps.executeQuery();
   while (rs.next()) {
 %>

 <a href='#'><%=rs.getString(1)%></a>
 <br />

 <%
  }
 %>
 <a href="index.jsp?opr=<%=totalPageCount +1%>">下一页</a>
 <a href="index.jsp?opr=<%=totalPageCount-1%>">上一页</a>
 <%
  } catch (SQLException e) {
   e.printStackTrace();
  }
  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();
   }
  }
 %>
</body>
</html>

posted @ 2018-01-11 17:09  kaluse天蝎  阅读(425)  评论(0编辑  收藏  举报