BootStrap 和JQuery 实现分页效果

BootStrap 和JQuery 实现分页效果
基于Ajax 实现前后端分离 ,分别在两个服务器进行数据交互 ,前端框架BootStrap ,简端脚本框架JQuery 。
后端用servlet简单获取数据库数据 ,利用filter过滤器实现跨域请求。

主要功能有 分页、多选框选择 新增 批量删除 更新 单个删除
分页:
BootStrap 和JQuery 实现分页效果_第1张图片
BootStrap 和JQuery 实现分页效果_第2张图片BootStrap 和JQuery 实现分页效果_第3张图片

多选:当前页面选择编号 为全选,下面选框都会打钩,取消全选,下面选框全不选,下面选框选满满多选会自动勾选,反之不选。
BootStrap 和JQuery 实现分页效果_第4张图片
BootStrap 和JQuery 实现分页效果_第5张图片
更新 :点击更新显示用户基本信息,编号无法改变。
BootStrap 和JQuery 实现分页效果_第6张图片

后端sevlet代码:


package com.powernode.ums.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.ums.domain.User;
import com.powernode.ums.service.UserService;
import com.powernode.ums.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

//注解方式获取servlet请求
@WebServlet(urlPatterns = {"/main","/getUserCode","/addUser", "/delete","/Update","/Updateinfomation"})
public class UserOprationServlet  extends HttpServlet {

    private UserService service = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");//设置请求和响应编码格式,防止乱码

        //getRequestURI()获取具体请求的servlet   lastIndexOf匹配最后匹配到的/ 下标   获得main
        String path = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
       try{
           if("main".equals(path)){
               System.out.println("前端请求到了main-----");
               //创建解析Java对象的工具对象
               ObjectMapper mapper = new ObjectMapper();
              //将被解析成JSON字符串的对象响应到前端
               response.getWriter().print(mapper.writeValueAsString(this.service.selectAll()));
           }else if ("getUserCode".equals(path)){
               System.out.println("前端请求到了getUserCode-----");
               response.getWriter().print(UUID.randomUUID().toString());
           } else if ("addUser".equals(path)) {
               System.out.println("前端请求到了addUser...");
               String usercode = request.getParameter("usercode");
               String fullname = request.getParameter("fullname");
               int age = Integer.parseInt(request.getParameter("age"));
               String email = request.getParameter("email");
               String sex = request.getParameter("sex");
               String address = request.getParameter("address");

               User user = new User(usercode, fullname, age, sex, email, address);

               response.getWriter().print(this.service.insertUser(user));
           } else if ("delete".equals(path)) {

               System.out.println("前端请求到了delete...");
               String type = request.getParameter("type");

               if ("batch".equals(type)) {
                   //批量删除
                   String[] delIds = request.getParameter("delIds").split("/");
            //调用service将数组传入dao
                   response.getWriter().print(this.service.batchDelete(delIds));
               } else {
                   System.out.println("前端请求到了deleteuser");
                   String  usercode = request.getParameter("usercode");
                   //单个删除
                   response.getWriter().print(this.service.deleteuser(usercode));
               }
           }else if("Update".equals(path)){
               System.out.println("前端请求到了Update");
               String usercode = request.getParameter("usercode");
               ObjectMapper mapper = new ObjectMapper();
               //将被解析成JSON字符串的对象响应到前端
               response.getWriter().print(mapper.writeValueAsString( this.service.showoneuser(usercode)));
           }else if("Updateinfomation".equals(path)){

               System.out.println("前端请求到了Updateinfomation");
               String usercode = request.getParameter("usercode");
               String fullname = request.getParameter("fullname");
               int age = Integer.parseInt(request.getParameter("age"));
               String email = request.getParameter("email");
               String sex = request.getParameter("sex");
               String address = request.getParameter("address");

               User user = new User(usercode, fullname, age, sex, email, address);

               boolean flag = this.service.Updateinfomation(user);
               response.getWriter().println(flag);

           }

       }catch (Exception e){
           e.printStackTrace();
       }
    }

}

后端dao层:

package com.powernode.ums.dao.impl;

import com.powernode.ums.dao.UserDao;
import com.powernode.ums.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() throws Exception {

        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");

        String sql = "select * from user";

        PreparedStatement ps = conn.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        List<User> users = new ArrayList<>();

        while (rs.next()) {
            User user = new User();
            user.setUserCode(rs.getString(1));
            user.setFullName(rs.getString(2));
            user.setAge(rs.getInt(3));
            user.setSex(rs.getString(4));
            user.setEmail(rs.getString(5));
            user.setAddress(rs.getString(6));
            users.add(user);
        }

        rs.close();
        ps.close();
        conn.close();

        return users;
    }

    @Override
    public boolean addUser(User user) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");

        String sql = "insert into user values (?,?,?,?,?,?)";

        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setString(1, user.getUserCode());
        ps.setString(2, user.getFullName());
        ps.setInt(3, user.getAge());
        ps.setString(4, user.getSex());
        ps.setString(5, user.getEmail());
        ps.setString(6, user.getAddress());

        int i = ps.executeUpdate();

        ps.close();
        conn.close();
        return i > 0;
    }

    @Override
    public boolean batchDelete(String[] delIds) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");

        StringBuffer sql = new StringBuffer();

        sql.append("delete from user where usercode in(");


        for (int i = 0; i < delIds.length; i++) {
            if (i == delIds.length - 1) {
                sql.append("?)");
            } else {
                sql.append("?,");
            }
        }
        PreparedStatement ps = conn.prepareStatement(sql.toString());


        for (int i = 0; i < delIds.length; i++) {
            ps.setObject(i+1,delIds[i]);
        }

        int i = ps.executeUpdate();

        ps.close();
        conn.close();

        return i > 0;
    }

    @Override
    public User showoneuser(String usercode) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");
        String sql = "select * from user where usercode = ?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, usercode);
        ResultSet rs = ps.executeQuery();

        User user = new User();

       if (rs.next()) {

            user.setUserCode(rs.getString(1));
            user.setFullName(rs.getString(2));
            user.setAge(rs.getInt(3));
            user.setSex(rs.getString(4));
            user.setEmail(rs.getString(5));
            user.setAddress(rs.getString(6));

        }

        rs.close();
        ps.close();
        conn.close();
        return user;

    }

    @Override
    public boolean Updateinfomation(User user) throws Exception {

        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");
        boolean flag = false;
        String sql = "update user set fullname=?,age=?,sex=?,email=?,address=? where usercode=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        if(ps!= null){
            flag = true;
        }
        ps.setString(1, user.getFullName());
        ps.setInt(2, user.getAge());
        ps.setString(3, user.getSex());
        ps.setString(4, user.getEmail());
        ps.setString(5, user.getAddress());
        ps.setString(6, user.getUserCode());
        ps.executeUpdate();

        return flag;
    }

    @Override
    public boolean deleteuser(String usercode) throws Exception {

        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ums?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", "root", "hx12345678");
        boolean flag = false;
        String sql = "delete from user where usercode = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,usercode);

        int rows = ps.executeUpdate();
        if(rows > 0){
            flag = true;
        }else{
           flag = false;
        }
        return flag;
    }

}


filter过滤器(解决跨域问题):

package com.powernode.ums.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;//父类强转子类
        //这两条语句就够了,网上filter写很多,其实这两条就包括了所有
        response.setHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest,response);
    }

    @Override
    public void destroy() {

    }
}

前端页面 ,Bootstrap前端框架实现:
(前端代码无须背,只要会用框架就行)


DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>title>
		<link href="static/css/bootstrap.min.css" rel="stylesheet" />
		<script type="text/javascript" src="js/jquery-3.4.1.min.js">script>
		<script type="text/javascript" src="static/js/bootstrap.min.js">script>
		<script src="js/ums.js">script>
	head>
	<body>
		
		<div class="container">
			<div id="user-message" class="alert alert-success" style="display: none;">
			    <a href="#" class="close" data-dismiss="alert">×a>
			    <span style="font-size: 30px; display: inline-block;width: 100%;text-align: center;">span>
			div>
			
			<div class="row">
				<div class="col-xs-12">
					<h1>用户详情h1>
				div>
			div>

			<div class="row">
				<div class="col-xs-4 col-xs-offset-8">
					<button type="button" class="btn btn-primary" data-toggle="modal"
						data-target="#addUserModal">新增用户button>
					<button type="button" class="btn btn-danger" id="btn-batchDel">批量删除button>
				div>
			div>


			<div class="row">
				<div class="col-xs-12">
					<table class="table table-hover">
						<thead>
							<tr>
								<th>
									
									<input type="checkbox" value="0"/>
									编号
								th>
								<th>姓名th>
								<th>年龄th>
								<th>性别th>
								<th>邮箱th>
								<th>地址th>
								<th>操作th>
							tr>
						thead>
						<tbody id="input_tbody">
							
						tbody>
					table>
				div>
			div>


			<div class="row" style="text-align: center;">
				<div class="col-xs-12">
					<ul class="pagination">
						
					ul>
				div>
			div>
		div>



		
		<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
			aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×button>
						<h4 class="modal-title" id="myModalLabel">用户添加h4>
					div>
					<div class="modal-body">
						<form class="form-horizontal" role="form" id="addModal-form">
							<div class="form-group">
								<label for="firstname" class="col-sm-2 control-label">编号:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="usercode" placeholder="请输入编号">
								div>
							div>
							<div class="form-group" style="display: none !important;">
								<div class="col-sm-10">
									<input type="text" class="form-control" id="hidden_usercode" name="usercode">
								div>
							div>

							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">姓名:label>
						  <div class="col-sm-10">
									<input type="text" class="form-control" id="fullname" name="fullname" placeholder="请输入姓名">
								div>
							div>

							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">年龄:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
								div>
							div>

							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">邮箱:label>
								<div class="col-sm-10">
						 		<input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
								div>
						 div>


						 <div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">性别:label>
								<div class="col-sm-10">
									<label class="radio-inline">
										<input type="radio" name="sex" id="male"
											value="" checked>label>
									<label class="radio-inline">
										<input type="radio" name="sex" id="female"
											value="">label>
								div>
							div>


							<div class="form-group">
						  <label for="lastname" class="col-sm-2 control-label">地址:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="address" name="address" placeholder="请输入地址">
								div>
							div>
						form>
					div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭button>
						<button type="button" class="btn btn-primary" id="addModal-submit">提交button>
					div>
				div>
			div>
		div>
	body>
	
	
	
	
		
		<div class="modal fade" id="UpdaUserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
			aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×button>
						<h4 class="modal-title" id="myModalLabel">用户更新h4>
					div>
					<div class="modal-body">
						<form class="form-horizontal" role="form" id="updateModal-form">
							<div class="form-group">
								<label for="firstname" class="col-sm-2 control-label">编号:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="updateusercode" placeholder="请输入编号">
								div>
							div>
							<div class="form-group" style="display: none !important;">
								<div class="col-sm-10">
									<input type="text" class="form-control" id="update_hidden_usercode" name="usercode">
								div>
							div>
	
							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">姓名:label>
						  <div class="col-sm-10">
									<input type="text" class="form-control" id="fullname" name="fullname" placeholder="请输入姓名">
								div>
							div>
	
							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">年龄:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
								div>
							div>
	
							<div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">邮箱:label>
								<div class="col-sm-10">
						 		<input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
								div>
						 div>
	
	
						 <div class="form-group">
								<label for="lastname" class="col-sm-2 control-label">性别:label>
								<div class="col-sm-10">
									<label class="radio-inline">
										<input type="radio" name="sex" id="male"
											value="" checked>label>
									<label class="radio-inline">
										<input type="radio" name="sex" id="female"
											value="">label>
								div>
							div>
	
	
							<div class="form-group">
						  <label for="lastname" class="col-sm-2 control-label">地址:label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="address" name="address" placeholder="请输入地址">
								div>
							div>
						form>
					div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭button>
						<button type="button" class="btn btn-primary" id="updateModal-submit">提交button>
					div>
				div>
			div>
		div>
	body>
html>


ums.js (整个代码的核心就是这个啦)
(使用了JQ会更简单uery 的 $.get()发法请求到前端 ,内存分页操作代码有待提高,将数据放入redis 会更简单)

const URL = `http://127.0.0.1:8080/ums`;


//被用户选中的id的
var delIds = ``;


//分页属性
var currentPage = 1; //当前页
var totalCount = 0; //总数据量
var pageSzie = 5; //每页显示条目数
var startIndex = 0; //内存分页的数据开始下标
var endIndex = 0; //内存分页的数据结束下标


//页面数据的数量
var pageCount = 0;

//分页操作
$(function() {

	getData();
	updateuser();
	updateuserinformatopn();
	deleteuserinfomation();
	$("ul.pagination").on('click', 'a[page-type]', function() {
		let type = $(this).attr("page-type");

		if (type == "firstPage") {
			currentPage = 1;
			getData();
		} else if (type == "lastPage") {
			currentPage = Math.ceil(totalCount / pageSzie);
			getData();
		} else if (type == "page") {
			currentPage = $(this).attr("page-num");
			getData();
		}
	})



	/*
		处理获取编号
	*/
	$("#addUserModal #usercode").focus(function() {
		/*去后台拿数据*/
		$.get(`${URL}/getUserCode`, function(data) {
			//给显示框赋值并且置灰
			$("#addUserModal #usercode").val(data).prop('disabled', true);
			//给隐藏域赋值
			$("#addUserModal #hidden_usercode").val(data)
		});
	})


	/*
		添加用户信息
	*/
	$('#addModal-submit').click(function() {

		$.post(`${URL}/addUser`,
			$('#addModal-form').serialize(),
			function(data) {
				//隐藏模态框
				$("#addUserModal").modal('hide');

				//清空数据
				$("#addUserModal :input").val('');
				//将编号恢复
				$("#addUserModal #usercode").prop('disabled', false);

				if (data == 'true') {
					message('添加用户成功');
				} else {
					message('添加用户失败');
				}
			})
	});



	/*
		全选
	*/
	$("input[type='checkbox']:eq(0)").click(function() {
		//获取全选按钮的value值
		var value = $(this).val();


		var inps = $("input[type='checkbox']:gt(0)");

		if (value == 0) {
			//将所有的checkbox设置为选中状态;
			inps.prop('checked', true);

			/*
				当前状态是未选中
				因为用户点击了,所以要改为选中状态
				设置全选按钮的值为1 代表已经被选取了
			*/
			$(this).val(1);

			//将全选的数据的有的id放入delids
			$.each(inps, function(index, input) {
				delIds += input.value + ",";
			});

		} else {
			inps.prop('checked', false);
			$(this).val(0);
			delIds = '';
		}
	})



	/*
		设置单选点击事件
	*/
	$("tbody").on('click', ':input', function() {
		/*
			找到 tbody下面的被选中的input
		 */
		var count = $("tbody input[type='checkbox']:checked").length;

		if (count == pageCount) {
			$("input[type='checkbox']:eq(0)").prop('checked', true).val(1);

		} else {
			$("input[type='checkbox']:eq(0)").prop('checked', false).val(0);
		}

	})


	/*
		批量删除
		将已经处理完毕的id发送给服务器。
	*/
	$("#btn-batchDel").click(function() {

		//清空delids
		delIds = '';

		var inputs = $("#input_tbody input[type='checkbox']:checked");


		$.each(inputs, function(index, input) {
			delIds += $(input).val();
		})



		if (delIds == '') {
			alert("您还没有选择任何数据...");
			return;
		}

		$.post(`${URL}/delete`, {
			"delIds": delIds,
			"type": "batch"
		}, function(data) {
			if (data == 'true') {
				message('删除用户成功');
			} else {
				message('删除用户失败');
			}
			//刷新
			getData();
		});
	})


	/*
	  更新用户
	*/


})



function message(msg) {
	//设置提示信息
	$('#user-message > span').text(msg);
	//显示信息提示框,下滑显示
	$('#user-message').slideDown(3000);
	//提示信息慢慢消失
	setTimeout(() => {
		$('#user-message').slideUp(3000);
	}, 3000);
}
// 整页面显示
function getData() {
	$.get(`${URL}/main`, function(data) {
		/*
			将字符串转换为JSON对象
		*/
		data = JSON.parse(data);


		//处理分页
		//初始化总数据量  22
		totalCount = data.length;


		//计算内存分页的开始下标
		startIndex = (currentPage - 1) * pageSzie;

		//计算内存分页的结束下标
		if (startIndex + pageSzie <= totalCount) {
			endIndex = startIndex + pageSzie - 1;
		}

		if (startIndex + pageSzie > totalCount) {
			endIndex = totalCount;
		}

		//每一次刷新都初始化页面数据变量
		pageCount = 0;

		/*
			循环迭代
		*/

		var mainData = "";
		$.each(data, function(index, user) {
			if (index >= startIndex && index <= endIndex) {
				pageCount++;


				mainData +=
					`
					
						
							${user.userCode}/>
							${user.userCode}
						
						${user.fullName}
						${user.age}
						${user.sex}
						${user.email}
						${user.address}
						
							
							
						
					
				`;
			}
		})

		$("tbody").html(mainData);


		//处理分页

		var pageUl = `
  • 首页
  • `
    ; for (let i = 1; i <= Math.ceil(totalCount / pageSzie); i++) { if (currentPage == i) { pageUl += `
  • ${i}
  • `
    ; } else { pageUl += `
  • ${i}">${i}
  • `
    ; } } pageUl += `
  • 末页
  • `
    ; $("ul.pagination").html(pageUl); }); } function deleteuserinfomation(){ $('tbody').on('click', 'button[btn-type="delete"]', function(){ if (confirm('确定执行删除吗?')){ $.post(`${URL}/delete`, { usercode: $(this).attr('data-user-code'), "type": "deletuser" }, function(data) { if (data == 'true') { message('删除用户成功'); } else { message('删除用户失败'); } //刷新 getData(); }); } }) } /* 更新用户 */ function updateuser() { $('tbody').on('click', 'button[btn-type="update"]', function() { $.post(`${URL}/Update`, { usercode: $(this).attr('data-user-code') }, function(data) { //显示模态框 $("#UpdaUserModal").modal('show'); var data = eval("(" + data + ")"); //转换为json对象 //设置用户编号 alert(data.userCode); $('#updateusercode').val(data.userCode).prop('disabled', true); $("#updateModal-form input:eq(1)").val(data.userCode); //设置姓名 $("#updateModal-form input:eq(2)").val(data.fullName); //设置年龄 $("#updateModal-form input:eq(3)").val(data.age); //设置邮箱 $("#updateModal-form input:eq(4)").val(data.email); //设置性别 if (data.sex == '男') { $("#updateModal-form input:eq(5)").prop('checked', true); } else { $("#updateModal-form input:eq(6)").prop('checked', true); } //设置地址 $("#updateModal-form input:eq(7)").val(data.address); }) }) } function updateuserinformatopn() { $('#updateModal-submit').click(function() { $.post(`${URL}/Updateinfomation`, $('#updateModal-form').serialize(), function(data) { if (data == 'true') { message("用户更新成功"); } else { message("用户更新成功"); } $("#UpdaUserModal").modal('hide'); getData(); }) }) }

    你可能感兴趣的:(bootstrap,jquery,servlet)