1. 程式人生 > >Intellij-IDEA搭建SrpingMVC+Spring+Mybatis+Bootstrap+分頁(二)

Intellij-IDEA搭建SrpingMVC+Spring+Mybatis+Bootstrap+分頁(二)

1.引入Bootstrap,優化登入頁面及註冊頁面

先引入bootstrap、jquery、jquery validate檔案和一張背景圖片
注:在引入bootstrap.js之前要先引入jquery
關於bootstrap具體如何使用,請百度學習一下:Bootstrap菜鳥教程
這裡寫圖片描述
login.jsp完整程式碼,登入頁面和註冊頁面寫了一起

<%@ page contentType="text/html;charset=UTF-8"%>
<%
    /*獲取工程路徑*/
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <title>登入頁面</title>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <!--用百度的靜態資源庫的cdn安裝bootstrap環境-->
    <!-- 新 Bootstrap 核心 CSS 檔案 -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--表單校驗JS:jquery.validate-->
    <script type="text/javascript" src="<%=basePath%>js/jquery.validate.min.js" ></script>
    <script type="text/javascript" src="<%=basePath%>js/login.js" ></script>
    <style type="text/css">
        body{background: url(<%=basePath%>img/4.jpg) no-repeat;background-size:cover;font-size: 16px;}
        .form{background: rgba(255,255,255,0.2);width:400px;margin:100px auto;}
        #login_form{display: block;}
        #register_form{display: none;}
        .fa{display: inline-block;top: 27px;left: 6px;position: relative;color: #ccc;}
        input[type="text"],input[type="password"]{padding-left:26px;}
        .checkbox{padding-left:21px;}
    </style>
    <script type="text/javascript">
        $(function () {
            if('${msg}'!=''){
                $("#register_form").css("display", "block");
                $("#login_form").css("display", "none");
                alert('${msg}');
            }
        });
    </script>
</head>
<body>
<div class="container">
    <div class="form row">
        <form action="<%=basePath%>user/login" method="post" class="form-horizontal col-sm-offset-3 col-md-offset-3" id="login_form">
            <h3 class="form-title">Login to your account</h3>
            <div class="col-sm-9 col-md-9">
                <div class="form-group">
                    <i class="fa fa-user fa-lg"></i>
                    <input class="form-control required" type="text" placeholder="LoginName" name="loginName" autofocus="autofocus" maxlength="20"/>
                </div>
                <div class="form-group">
                    <i class="fa fa-lock fa-lg"></i>
                    <input class="form-control required" type="password" placeholder="Password" name="password" maxlength="8"/>
                </div>
                <div class="form-group">
                    <label class="checkbox">
                        <input type="checkbox" name="remember" value="1"/> Remember me
                    </label>
                    <hr />
                    <a href="javascript:;" id="register_btn" class="">Create an account</a>
                </div>
                <div class="form-group">
                    <input type="submit" class="btn btn-success pull-right" value="Login "/>
                </div>
            </div>
        </form>
    </div>

    <div class="form row">
        <form action="<%=basePath%>user/register" method="post" class="form-horizontal col-sm-offset-3 col-md-offset-3" id="register_form">
            <h3 class="form-title">Login to your account</h3>
            <div class="col-sm-9 col-md-9">
                <div class="form-group">
                    <i class="fa fa-user fa-lg"></i>
                    <input class="form-control required" type="text" placeholder="Name" name="name" autofocus="autofocus"/>
                </div>
                <div class="form-group">
                    <i class="fa fa-user fa-lg"></i>
                    <input class="form-control required" type="text" placeholder="Age" name="age" autofocus="autofocus"/>
                </div>
                <div class="form-group">
                    <i class="fa fa-user fa-lg"></i>
                    <input class="form-control required" type="text" placeholder="LoginName" name="loginName" autofocus="autofocus"/>
                </div>
                <div class="form-group">
                    <i class="fa fa-lock fa-lg"></i>
                    <input class="form-control required" type="password" placeholder="Password" id="register_password" name="password"/>
                </div>
                <div class="form-group">
                    <i class="fa fa-check fa-lg"></i>
                    <input class="form-control required" type="password" placeholder="Re-type Your Password" name="rpassword"/>
                </div>
                <div class="form-group">
                    <input type="submit" class="btn btn-success pull-right" value="Sign Up "/>
                    <input type="button" class="btn btn-info pull-left" id="back_btn" value="Back"/>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
</html>

login.js,註冊時做表單校驗

$().ready(function() {
    $("#login_form").validate({
        rules: {
            loginName: "required",
            password: {
                required: true,
                minlength: 1
            },
        },
        messages: {
            loginName: "請輸入登入名",
            password: {
                required: "請輸入密碼"

            },
        }
    });
    $("#register_form").validate({
        rules: {
            loginName: "required",
            age:{
                digits:true,
                min:0,
                max:120
            },
            password: {
                required: true,
                minlength: 1
            },
            rpassword: {
                equalTo: "#register_password"
            }
        },
        messages: {
            name:"請輸入您的姓名",
            loginName: "請輸入登入名",
            age:{
                required:"請輸入您的年齡"
            },
            password: {
                required: "請輸入密碼"
            },
            rpassword: {
                equalTo: "兩次密碼不一樣",
                required: "請再次輸入密碼"
            }
        }
    });
});
$(function() {
    $("#register_btn").bind("click",function () {
        $("#register_form").css("display", "block");
        $("#login_form").css("display", "none");
    });
    $("#back_btn").bind("click",function () {
        $("#register_form").css("display", "none");
        $("#login_form").css("display", "block");
    });
});

啟動應用,訪問localhost:8080
這裡寫圖片描述
點選 Create an account 顯示註冊頁面
這裡寫圖片描述
登入試試,賬號admin,密碼123
這裡寫圖片描述

2.註冊功能實現

註冊校驗規則看login.js檔案,不符合校驗規則會出現對應的提示
這裡寫圖片描述
使用者註冊介面

    /**
     * 使用者註冊
     * @param userInfo
     * @return
     */
    @RequestMapping("/register")
    public String register(UserInfo userInfo,Model model){
        try {
            UserInfo user = userInfoService.selectUserByLoginName(userInfo.getLoginName());
            if(user!=null){
                model.addAttribute("msg","註冊失敗,該登入名已存在!");
            }else{
                userInfoService.insertUser(userInfo);
                model.addAttribute("msg","註冊成功,請登入!");
            }
        }catch (Exception e){
            model.addAttribute("msg","註冊失敗!");
            e.printStackTrace();
        }
        return "/login";
    }

註冊一個賬號試試
這裡寫圖片描述
點選Sing up提示註冊成功,現在到資料庫看下
這裡寫圖片描述

3.系統主介面設計##

垂直方向分3層,第一層顯示當前使用者資訊和一個退出按鈕,第二層是導航欄資訊,第三層是資料主體部分

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    /*獲取工程路徑*/
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <title>主介面</title>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <!-- 新 Bootstrap 核心 CSS 檔案 -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#userManager").attr("class","active");
            $("#frm_right").attr("src","<%=basePath%>user/selectAll");
        });

        function menuClick(obj,url){
            if(obj==1){
                $("#userManager").attr("class","active");
                $("#roleManager").attr("class","");
                $("#menuManager").attr("class","");
            }
            if(obj==2){
                $("#roleManager").attr("class","active");
                $("#userManager").attr("class","");
                $("#menuManager").attr("class","");
            }
            if(obj==3){
                $("#menuManager").attr("class","active");
                $("#roleManager").attr("class","");
                $("#userManager").attr("class","");
            }
            $("#frm_right").attr("src",url);
        }

        function loginOut(obj){
            if (confirm('您確定要退出系統嗎?')) {
                obj.href = "<%=basePath%>user/loginOut";
                obj.onclick = "";
                obj.click();
            }
        }
        //主介面自適應高度   這個函式要在frm_right載入完了呼叫才有用
        function mainHeight() {
            var ifm= document.getElementById("frm_right");
            var subWeb =document.frames ? document.frames["frm_right"].document : ifm.contentDocument;
            if(ifm != null && subWeb != null) {
                var hg=subWeb.body.scrollHeight;
                ifm.height = hg<600?600:hg;
            }
        }
    </script>
</head>
<body>
<%--導航欄和使用者資訊--%>
<div>
    <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <ul class="nav navbar-nav navbar-left">
                <li><a href="#">您好:${userInfo.name},歡迎登入,當前賬號為:${userInfo.loginName}</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="javascript:void(0)" onclick="loginOut(this)"><span class="glyphicon glyphicon-user"></span> 退出</a></li>
            </ul>
        </div>
    </nav>
    <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#"></a>
            </div>
            <div>
                <ul class="nav navbar-nav" id="top" style="font-size: 16px;">
                    <li id="userManager"><a href="javascript:void(0)" onclick="menuClick(1,'<%=basePath%>user/selectAll')">使用者管理</a></li>
                    <li id="roleManager"><a href="javascript:void(0)" onclick="menuClick(2,'<%=basePath%>user/roleManager')">許可權管理</a></li>
                    <li id="menuManager"><a href="javascript:void(0)" onclick="menuClick(3,'<%=basePath%>user/menuManager')">選單管理</a></li>
                </ul>
            </div>
        </div>
    </nav>
</div>
<%--下方主介面--%>
<div style=" text-align: center;height: 100%;">
    <iframe frameborder="0" name="frm_right" id="frm_right"	width="100%" scrolling="no" src="" style="margin:0px auto 0px auto; background-color: white;padding: 0px" ></iframe>
</div>
</body>
</html>

在views目錄下新建userManager.jsp、roleManager.jsp、menuManager.jsp,這是三個導航欄的主介面,這裡寫使用者管理,其他不管

userManager.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    /*獲取工程路徑*/
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <!-- 新 Bootstrap 核心 CSS 檔案 -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        //主介面高度自適應
        $(function () {
            //top代表頂層視窗物件
            top.mainHeight();
            if('${msg}'!=''){
                alert('${msg}');
            }
        });
        //查詢事件
        function findData(){
            $('#currentPage').val('1');
            document.forms[0].submit();
        }
        //清空查詢條件
        function clearP(){
            $("#name").val("");
            $("#loginName").val("");
        }

        //刪除使用者
        function del(id) {
            if(confirm("確定要刪除該使用者嗎?")){
                $.ajax({
                    url:"<%=basePath%>user/del",
                    type:"post",
                    dataType:"json",
                    data:{id:id},
                    success:function () {
                        alert("刪除成功!");
                        $("#myform").submit();
                    },
                    error:function () {//不知道為什麼有時會走error
                        alert("刪除成功!");
                        $("#myform").submit();
                    }
                });
            }
        }
        //編輯使用者 先獲取當前ID使用者資訊
        function edit(id) {
            $.ajax({
                url:"<%=basePath%>user/selectUserById",
                type:"post",
                dataType:"json",
                data:{id:id},
                success:function (data) {
                    $("#editModal").modal("show");
                    $("#name2").val(data.name);
                    $("#age2").val(data.age);
                    $("#loginName2").val(data.loginName);
                    $("#rpassword2").val(data.password);
                    $("#password2").val(data.password);
                    $("#myid").val(data.id);
                },
                error:function () {
                    alert("獲取使用者資料失敗!");
                }
            });
        }
    </script>
</head>
<body>
<div class="table-responsive">
    <form class="form-inline" role="form" action="<%=basePath%>user/selectAll" method="post" id="myform">
    <div style="margin-left: 80px;">
        姓名:<input type="text" name="name" id="name" value="${userInfo1.name}" class="form-control" style="width: 120px;">
        賬號:<input type="text" name="loginName" id="loginName" value="${userInfo1.loginName}" class="form-control" style="width: 120px;">
        <input type="button" onclick="findData();" class="btn btn-info" value="查詢"/>
        <input type="button" onclick="clearP();" class="btn btn-info" value="清空"/>
        <input type="button" data-toggle="modal" data-target="#addModal" class="btn btn-info" value="新增"/>
    </div>
    <hr style="margin-top: 10px;"/>
    <div style="margin-left: 20px;">
        <table class="table table-hover">
            <thead>
            <tr style="text-align: center">
                <th style="text-align: center">序號</th>
                <th style="text-align: center">姓名</th>
                <th style="text-align: center">年齡</th>
                <th style="text-align: center">賬號</th>
                <th style="text-align: center">密碼</th>
                <th style="text-align: center">操作</th>
            </tr>
            </thead>
            <tbody>
            <c:if test="${!empty userList }">
                <c:forEach items="${userList}" var="user" varStatus="status">
                    <tr style="text-align: center">
                        <td>${user.id}</td>
                        <td>${user.name }</td>
                        <td>${user.age }</td>
                        <td>${user.loginName }</td>
                        <td>${user.password }</td>
                        <td>
                            <button type="button" class="btn btn-success" onclick="edit('${user.id }')">編輯</button>
                            <button type="button" class="btn btn-danger" onclick="del('${user.id }')">刪除</button>
                        </td>
                    </tr>
                </c:forEach>
            </c:if>
            </tbody>
        </table>
        <div >
           <jsp:include page="/common/page.jsp"/>
        </div>
    </div>
</form>
</div>
<!-- 新增使用者模態框(Modal) -->
<form action="<%=basePath%>user/addUser" method="post" id="register_form1">
    <div class="modal fade" id="addModal" 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">
                        &times;
                    </button>
                    <h4 id="mytitle" class="modal-title" id="myModalLabel">
                        新增使用者
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" id="name1" placeholder="Name" name="name" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" placeholder="Age" id="age1" name="age" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" placeholder="LoginName" id="loginName1" name="loginName" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-lock fa-lg"></i>
                        <input class="form-control required" placeholder="Password" id="password1" name="password"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-check fa-lg"></i>
                        <input class="form-control required" placeholder="Re-type Your Password" id="rpassword1" name="rpassword"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉
                    </button>
                    <button type="submit" class="btn btn-info">
                        確認
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</form>
<!-- 編輯使用者模態框(Modal) -->
<form action="<%=basePath%>user/addUser" method="post" id="editModalForm">
    <input type="hidden" id="myid" name="myid"/>
    <div class="modal fade" id="editModal" 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">
                        &times;
                    </button>
                    <h4 id="mytitle1" class="modal-title" id="myModalLabel1">
                        編輯使用者
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" id="name2" placeholder="Name" name="name" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" placeholder="Age" id="age2" name="age" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-user fa-lg"></i>
                        <input class="form-control required" type="text" placeholder="LoginName" id="loginName2" name="loginName" autofocus="autofocus"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-lock fa-lg"></i>
                        <input class="form-control required" placeholder="Password" id="password2" name="password"/>
                    </div>
                    <div class="form-group">
                        <i class="fa fa-check fa-lg"></i>
                        <input class="form-control required" placeholder="Re-type Your Password" id="rpassword2" >
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉
                    </button>
                    <button type="submit" class="btn btn-info">
                        確認
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</form>
</body>
</html>


roleManager.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div style="text-align: center">這裡是許可權管理頁面!</div>
</body>
</html>

menuManager.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div style="text-align: center">這裡是選單管理頁面</div>
</body>
</html>

UserInfoController,實現基本的增刪改查功能

package com.xujd.controller;

import com.xujd.model.UserInfo;
import com.xujd.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserInfoController{
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 使用者登入
     * @param userInfo
     * @return
     */
    @RequestMapping("/login")
    public String login(UserInfo userInfo, HttpServletRequest request, Model model){
        String msg="";
        //根據登入賬號判斷該使用者是否存在
        UserInfo user = userInfoService.selectUserByLoginName(userInfo.getLoginName());
        if(user==null){
            msg="該使用者不存在!";
        }else{
            if(user.getPassword().equals(userInfo.getPassword())){
                /*將使用者資訊放入session*/
                request.getSession().setAttribute("userInfo",user);
                //獲取sessionid
                String sessionId=request.getSession().getId();
                model.addAttribute("sessionId",sessionId);
                //進入主介面
                return "/main";
            }else{
                msg="密碼錯誤!";
            }
        }
        model.addAttribute("msg",msg);
        return "/login";
    }
    /**
     * 使用者註冊
     * @param userInfo
     * @return
     */
    @RequestMapping("/register")
    public String register(UserInfo userInfo,Model model){
        try {
            UserInfo user = userInfoService.selectUserByLoginName(userInfo.getLoginName());
            if(user!=null){
                model.addAttribute("msg","註冊失敗,該登入名已存在!");
            }else{
                userInfoService.insertUser(userInfo);
                model.addAttribute("msg","註冊成功,請登入!");
            }
        }catch (Exception e){
            model.addAttribute("msg","註冊失敗!");
            e.printStackTrace();
        }
        return "/login";
    }

    /**
     * 退出系統
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request){
        //清空session
        request.getSession().invalidate();
        return "login";
    }

    /**
     * 新增或編輯使用者資訊
     * @param userInfo
     * @param model
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(UserInfo userInfo,Model model,String myid){
        try {
            UserInfo user = userInfoService.selectUserByLoginName(userInfo.getLoginName());
            if(user!=null){
                model.addAttribute("msg","操作失敗,該登入名已存在!");
            }else{
                if(myid!=null&&!"".equals(myid)){//myid存在表示編輯操作
                    userInfo.setId(Integer.parseInt(myid));
                    userInfoService.updateUser(userInfo);
                }else{
                    userInfoService.insertUser(userInfo);
                }
                model.addAttribute("msg","操作成功!");
            }
        }catch (Exception e){
            model.addAttribute("msg","操作失敗!");
            e.printStackTrace();
        }
        return "redirect:/user/selectAll";
    }

    /**
     * 根據ID獲取使用者
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("selectUserById")
    @ResponseBody
    public UserInfo selectUserById(int id,Model model){
        UserInfo userInfo = userInfoService.selectUserById(id);
        return userInfo;
    }

    /**
     * 刪除使用者
     * @param id 使用者ID
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public String del(int id){
        try {
            userInfoService.deleteUser(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 許可權管理
     * @return
     */
    @RequestMapping("roleManager")
    public String roleManager(){
        return "roleManager";
    }

    /**
     * 選單管理
     * @return
     */
    @RequestMapping("menuManager")
    public String menuManager(){
        return "menuManager";
    }
    /**
     * 獲取所有使用者
     * @return
     */
    @RequestMapping("/selectAll")
    public String selectAll(Model model,UserInfo userInfo){
        model.addAttribute("userList",userInfoService.selectUserByParams(userInfo));
        model.addAttribute("userInfo1",userInfo);
        return "/userManager";
    }
}

啟動應用,訪問localhost:8080,並登入,可以看到主介面為:
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
新增使用者
這裡寫圖片描述
可以看到使用者已經成功新增到資料庫了
這裡寫圖片描述
查詢
這裡寫圖片描述
編輯
這裡寫圖片描述
點選確認
這裡寫圖片描述
刪除功能就不截圖演示了,到這裡使用者管理的增刪改查已經完成,還剩一個分頁功能。

4.分頁功能的實現

在model包下新增PageUtil

package com.xujd.model;

import java.util.List;

/**
 * 分頁工具類
 *
 * @author XuJD
 *
 */
public class PageUtil {
    /**
     * 當前頁 預設為1
     */
    private int currentPage=1;

    /**
     * 每頁顯示的記錄數  預設為10條
     */
    private int pageSize = 10;

    /**
     * 總頁數
     */
    private int totalPage;

    /**
     * 總記錄數
     */
    private int totalRecord;

    /**
     * 起始記錄
     */
    private int startRow;

    /**
     * 終止記錄
     */
    private int endRow;

    /**
     * 上一頁
     */
    private int upPage;

    /**
     * 下一頁
     */
    private int downPage;

    /**
     * 訪問路徑
     */
    private String accessUrl;

    /**
     * 頁面需要顯示的資料集合
     */
    private List objectLists;


    /**
     * 當前頁頁碼
     *
     * @param currentPage
     */
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getCurrentPage() {
        return currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 總頁數,根據總記錄數計算得出
     *
     * @return
     */
    public int getTotalPage() {
        return this.totalRecord % this.pageSize == 0 ? this.totalRecord
                / this.pageSize : (this.totalRecord / this.pageSize) + 1;
    }
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    /**
     * 總記錄數
     *
     * @return
     */
    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }

    /**
     * 起始記錄行
     *
     * @return
     */
    public int getStartRow() {
        return (this.currentPage - 1) * this.pageSize;
    }

    /**
     * 結束記錄行
     *
     * @return
     */
    public int getEndRow() {
        return this.currentPage * this.pageSize;
    }

    /**
     * 上一頁
     *
     * @return
     */
    public int getUpPage() {
        return (this.currentPage == 1) ? 1 : (this.currentPage - 1);
    }

    /**
     * 下一頁
     *
     * @return
     */
    public int getDownPage() {
        return (this.currentPage == this.totalPage) ? this.totalPage
                : (this.currentPage + 1);
    }

    /*
     * 結果記錄集
     */
    public List getObjectLists() {
        return objectLists;
    }

    public void setObjectLists(List objectLists) {
        this.objectLists = objectLists;
    }

}

改造一下selectAll介面

    /**
     * 獲取所有使用者
     * @return
     */
    @RequestMapping("/selectAll")
    public String selectAll(Model model,UserInfo userInfo,PageUtil pageP){
        //獲取所有資料數量
        int count = userInfoService.selectUserCount();
        PageUtil page = new PageUtil();
        //pageSize預設為10  currentPage預設為1
        page.setPageSize(pageP.getPageSize());
        page.setCurrentPage(pageP.getCurrentPage());
        //mysql中用 --這裡用limit a,b 去分頁,資料量比較大時不推薦limit
        //a表示起始行,b表示數量,如 limit 0,5 表示查5條資料,從資料庫中的第一條查起
        userInfo.setStartRow(page.getStartRow());
        userInfo.setEndRow(page.getEndRow()-page.getStartRow());
        //分頁查詢資料
        List<UserInfo> userList = userInfoService.selectUserByParams(userInfo);
        //設定所有使用者數量  如果有查詢條件則以查詢結果數量為準,不然為所有數量
        if((userInfo.getName()!=null&&!"".equals(userInfo.getName()))
                ||(userInfo.getLoginName()!=null&&!"".equals(userInfo.getLoginName()))){
            page.setTotalRecord(userList.size());
        }else{
            page.setTotalRecord(count);
        }
        model.addAttribute("page1",page);
        model.addAttribute("userList",userList);
        model.addAttribute("userInfo1",userInfo);
        return "/userManager";
    }

在common包下新增page.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    /*獲取工程路徑*/
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!-- 新 Bootstrap 核心 CSS 檔案 -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
    .btn {
        /*color: rgb(50, 151, 233);*/
        /*background-color: #F6F6F6;*/
        cursor: pointer;
        float: none;
        margin-left: auto;
        padding: 5px 10px;
    }
</style>
<script type="text/javascript">
    function doSubmitForm(value) {
        if (isNaN(value)) {
            alert("請輸入0-9的數字!");
            document.getElementById('page').value = "";
            return false;
        } else if (value === null || value === "" || value <= 0) {
            document.getElementById("currentPage").value = 1;
        } else if (parseInt(value) >parseInt('${requestScope.page1.totalPage}')) {
            document.getElementById("currentPage").value = '${requestScope.page1.totalPage}';
        } else {
            document.getElementById("currentPage").value = value;
        }
        document.forms[0].submit();
    }
    function chageSize() {
        $('#currentPage').val('1');
        document.forms[0].submit();
    }
</script>
<table style="font-size: 12px;" align="right">
    <tr>
        <c:if test="${requestScope.page1.totalRecord > 0}">
            <td style="border: 0;">
                共<span class='totalRecord'>${requestScope.page1.totalRecord}條記錄&nbsp;&nbsp;每頁
                <select name="pageSize" id="pageSize" onchange="chageSize()" title="">
                    <option value="5"  <c:if test="${requestScope.page1.pageSize == 5}">selected</c:if>>5</option>
                    <option value="10" <c:if test="${requestScope.page1.pageSize == 10}">selected</c:if>>10</option>
                    <option value="15" <c:if test="${requestScope.page1.pageSize == 15}">selected</c:if>>15</option>
                    <option value="20" <c:if test="${requestScope.page1.pageSize == 20}">selected</c:if>>20</option>
                    <option value="30" <c:if test="${requestScope.page1.pageSize == 30}">selected</c:if>>30</option>
                </select>
                條&nbsp;&nbsp;第
                ${requestScope.page1.currentPage}
                頁/共
                ${requestScope.page1.totalPage}
                頁
                <input type="button" class="btn addNewButton btn-info" value="首頁"
                       onclick="<c:if test="${requestScope.page1.totalPage > 1}">
                               doSubmitForm(getElementById('firstPage').value);</c:if>"/>
                <input type="hidden" value="${1}" id="firstPage"/>


                <c:if test="${requestScope.page1.currentPage > 1 &&
                    requestScope.page1.currentPage <= requestScope.page1.totalPage}">
                    <input type="button" class="btn addNewButton btn-info" value="上一頁"
                           onclick="doSubmitForm(getElementById('upPage').value);"/>
                    <input type="hidden" value="${requestScope.page1.upPage}"
                           id="upPage"/>
                </c:if>

                <c:if test="${requestScope.page1.currentPage >= 1 &&
                    requestScope.page1.currentPage < requestScope.page1.totalPage}">
                    <input type="button" class="btn addNewButton btn-info" value="下一頁"
                           onclick="doSubmitForm(getElementById('downPage').value);"/>
                    <input type="hidden" value="${requestScope.page1.downPage}" id="downPage"/>
                </c:if>

                <input type="button" class="btn addNewButton btn-info" value="末頁"
                       onclick="<c:if test="${requestScope.page1.totalPage > 1 }">
                               doSubmitForm(getElementById('endPage').value);</c:if>"/>
                <input type="hidden" value="${requestScope.page1.totalPage}" id="endPage"/>
                轉到
                <input type="text" style="width:30px;" id="page" size="2" title="">
                頁
                <input type="button" value="GO" class="btn addNewButton btn-info"
                       onclick="<c:if test="${requestScope.page1.totalPage > 1}">
                               doSubmitForm(getElementById('page').value);</c:if>">
                <input type="hidden" name="currentPage" id="currentPage"
                       value="${requestScope.page1.currentPage}"/>
            </td>
        </c:if>
        <c:if test="${requestScope.page1.totalRecord == 0}">
            <td colspan="99" style="border: 0;">
                <div align="left">
                    <span style="color: red">沒有符合條件的記錄,請輸入條件後重試!</span>
                </div>
            </td>
        </c:if>
    </tr>

</table>


在userManager頁面引入page.jsp
這裡寫圖片描述
最後改下sql,在原有的基礎上做了個limit過濾

這裡寫圖片描述
重啟應用,訪問localhost:8080,並登入,可以看到已經成功分頁了
這裡寫圖片描述
點選下一頁,可以看到已經獲取第二頁資料了
這裡寫圖片描述

對於分頁還不是很清楚的小夥伴認真閱讀page.jsp和PageUtil類,還有兩個重要的引數:當前頁(currentPage)和pageSize,因為後端都是通過這兩個引數做處理去獲取資料的

到這裡整個系統的主介面設計、分頁相關功能都已經完成了,是時候分享一波原始碼了