bootstrap+servlet+ajax实现完整的上下翻页例子

我这个固定1~5页,想要随下一页增加而加,这一点,先理解清楚,上下翻页的原理。就可以自行实现了,下面,是我实现上下翻页的完整例子。

连接数据库的例子省略,这个可自行查找。这里就不反复提了。

1、Mysql【注意,表中的数据我在java的映射中并没有写完整,可自行补充】

说很多,起始只是想说,这里有代码,里面部分会造成误会,重点是为了理解思想,想要完善也是可以的。

# Host: 127.0.0.1  (Version 5.5.13)
# Date: 2019-07-24 17:52:50
# Generator: MySQL-Front 6.1  (Build 1.26)


#
# Structure for table "admin"
#

DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `adminName` varchar(255) DEFAULT NULL,
  `admindat` varchar(255) DEFAULT NULL,
  `adminIs` varchar(255) DEFAULT NULL,
  `pubtitle` varchar(255) DEFAULT NULL,
  `toPublic` text,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;

#
# Data for table "admin"
#

INSERT INTO `admin` VALUES (1,'admin','2019-1-1','yes','第一个标题','今天天气不错,呜呜呜呜呜呜呜呜无无无无'),(2,'admin','2018','yes','第二个标题','dsfsadsssssssssssssssssssssssss'),(3,'sdfs','sdfsd','sdfs','第三个标题','asdasda'),(4,'sdfs','assssssssss','aaaaaaaaaaaaaaaaaaaaa','第四个标题','dddddddddddddddddddddddd'),(5,'fffff','fffffffffffff','ffffffffffffff','第五个标题','ffffffffffffffffffffffffffffffff'),(6,'admin','2019-03-05 00:39:51','yes','第六个标题','春天还没来到?就已经到了秋天!!!!!!!!!!!'),(7,'7','7','7','7','7'),(8,'8','8','8','8','8'),(9,'9','9','9','9','9'),(10,'10','10','10','10','10'),(11,'11','11','11','11','11'),(12,'12','12','12','12','12');

2、java映射类:

package table;

public class T_Admin {
    //
    private String id;
    private String name;
    private String title;
//set和get方法自行生成
    
}

3、查询数据并实现JSON化:

package test.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import table.T_Admin;

public class SelectUtil {
    public JSONArray selectLimit(int key,int num){
        Connection connection = ConnectDB.getConnectDB();
        PreparedStatement statement;
        ResultSet set;
        List<T_Admin> list = new ArrayList<T_Admin>();
        JSONArray array = new JSONArray();
        String sql = "select *from admin limit "+key+","+num+";";
        T_Admin admin;
        
        try {
             statement = connection.prepareStatement(sql);
             set = statement.executeQuery();
             while (set.next()) {
                admin = new T_Admin();
                admin.setId(set.getString("id"));
                admin.setName(set.getString("adminName"));
                admin.setTitle(set.getString("pubtitle"));
                System.out.println("id:"+admin.getId());
                list.add(admin);    
            }
             //将list转换为json
             for (int i = 0; i < list.size(); i++) {
                T_Admin admin2 = list.get(i);
                JSONObject object = JSONObject.fromObject(admin2);
                array.add(object);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return array;
    }
    
    /**
     * 统计总的有多少条记录
     */
    public String countNum(){
        Connection connection = ConnectDB.getConnectDB();
        String sql = "select count(*) num from admin";
        String n = null;
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet set = statement.executeQuery();
            while (set.next()) {
                 n = set.getString("num");
            }
            System.err.println(n);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return n;
    }
    
    
    public static void main(String[] args) {
        SelectUtil selectUtil = new SelectUtil();
        selectUtil.selectLimit(0,3);
        selectUtil.countNum();
    }
}

4、servlet实现前后交互:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import test.utils.SelectUtil;


public class Page extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public Page() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String key = request.getParameter("key");
        String num = request.getParameter("num");
        System.out.println(key+num);
        SelectUtil selectUtil = new SelectUtil();
        //设定一个默认,以防出错
        if(num==null||num.equals("")){num="4";}
        if(key.equals("")||key==null||Integer.parseInt(key)<0){key="0";}
        JSONArray list = selectUtil.selectLimit(Integer.parseInt(key),Integer.parseInt(num));
        session.setAttribute("num", selectUtil.countNum());
        System.out.println(list);
        out.print(list);
        out.flush();
        out.close();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

5、前端jsp实现ajax等:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>分页</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">  
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
        
        
        <h2 id="con">
                Heading
            </h2>
            <p>
                Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.
            </p>
            <p>
                 <a class="btn" href="javascript:clickA(0);">View details »</a>
        </p>
        
        
        <!-- 利用异步请求,使用拼接,href可以不使用,然后将内容加载 -->
            <ul class="pagination">
                <li>
                     <a id="prev" href="javascript:prevpage(0,3);">Prev</a>
                </li>
                <li>
                     <a href="javascript:clickA(0,4);">1</a>
                </li>
                <li>
                     <a href="javascript:clickA(3,4);">2</a>
                </li>
                <li>
                     <a href="javascript:clickA(6,4);">3</a>
                </li>
                <li>
                     <a href="javascript:clickA(9,4);">4</a>
                </li>
                <li>
                     <a href="javascript:clickA(12,4);">5</a>
                </li>
                <li class="a1">
                     <a id="next" href="javascript:nextpage(0);">Next</a><!-- 获取本页面翻页之后传过来的值 -->
                </li>
            </ul>
                <!-- 实现跳转到第x页 -->
                <div class="form-group">
                     <button type="button" class="btn btn-default" onclick="javascript:skip();">跳转</button>
                    <div class="col-sm-1">
                        <input type="text" class="form-control" id="skip" />
                    </div>
                </div>
        </div>
    </div>
</div>
<!--  -->
<script type="text/javascript">
function clickA(key,num){
    $(".h").empty();
    $(".p1").empty();
    $.ajax({
        type : "post",
        async : true,            //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
        url : "Page",    //请求发送到Page处
        data : {'key':key,'num':num},
        dataType : "json",        //返回数据形式为json
        success : function(result) {
            //请求成功时执行该函数内容,result即为服务器返回的json对象
                for(var k in result){
                //将获得的数据加入col-md-12 column
                $("#con").before("<h2 class='h'>"+result[k].title+"</2><p class='p1'>"+result[k].name+"</p><p class='p1'><a class='btn' href='javascript:clickA(0);'>View details »</a>"+"</p>");
                //改变a标签prev的属性
                $("#prev").attr("href","javascript:prevpage("+key+","+num+")");
                $("#next").attr("href","javascript:nextpage("+key+","+num+")");
                }    
        },
        error : function(XMLHttpRequest, textStatus,errorMsg) {
            //请求失败时执行该函数
            alert("错误码:"+XMLHttpRequest.status);
            alert("错误状态:"+XMLHttpRequest.readyState);
            alert("数据请求数据失败!"+errorMsg);
        }
    });   
}//函数结束
//实现下一页功能,一、获取a的key,二、将获得的key+3
function nextpage(key,num){
    key=key+num;
    clickA(key,num);
}
//翻页,上一页,由于在clickA中实现动态改变a标签的属性,所以这里就不需要担心其不会跟着next等变化了
function prevpage(prev,num){
    if(prev==0||num<prev){clickA(0,num);}else{
        prev = prev-num;
        clickA(prev);
    }    
}
//实现根据输入的页数跳转
function skip(){
    var s = $("#skip").val();
    if(s<=0){
        s=0;
        }else{
            clickA(s);
        }
}
//默认加载第一页,每页四条数据
clickA(0,4);
</script>
</body>
</html>

实际效果:

 

posted @ 2019-07-24 18:04  CiscoLee  阅读(817)  评论(0编辑  收藏  举报