ssm项目---人事管理系统:分页示例

概要说明:最近做了一个ssm项目—人事管理系统

现在分享一下对User的分页查询

效果图如下:

ssm项目---人事管理系统:分页示例_第1张图片


代码示例

1. 首先建立一个Page类,应包含每页显示的记录数,总页数,当前页,总记录数,和一个list对象,起始位置

package com.su.util;

import java.util.List;

public class Page {
     
    public static final int PAGESIZE = 3;  //每页显示的记录数
    private Integer totalPages;     //总页数
    private Integer currentPage;    //当前页
    private Integer tatalNums;      //总记录数
    private List list;             //list对象
    private Integer firstResult;   //起始位置
    public Integer getFirstResult() {
        return firstResult;
    }
    public void setFirstResult(Integer firstResult) {
        this.firstResult = firstResult;
    }
    public static int getPagesize() {
        return PAGESIZE;
    }
    public Integer getTotalPages() {
        return totalPages;
    }
    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }
    public Integer getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }
    public Integer getTatalNums() {
        return tatalNums;
    }
    public void setTatalNums(Integer tatalNums) {
        this.tatalNums = tatalNums;
    }
    public List getList() {
        return list;
    }
    public void setList(List list) {
        this.list = list;
    }
}


2. 建立一个user类

package com.su.domain;

import java.util.Date;

public class User {
     
    private Integer userId;   //id
    private String loginName; //登录名
    private String loginPwd;  //登录密码
    private Integer userStatus;  //用户状态
    private Date userCreateDate;  //创建时间
    private String userName;      //用户名
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getLoginPwd() {
        return loginPwd;
    }
    public void setLoginPwd(String loginPwd) {
        this.loginPwd = loginPwd;
    }
    public Integer getUserStatus() {
        return userStatus;
    }
    public void setUserStatus(Integer userStatus) {
        this.userStatus = userStatus;
    }
    public Date getUserCreateDate() {
        return userCreateDate;
    }
    public void setUserCreateDate(Date userCreateDate) {
        this.userCreateDate = userCreateDate;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }


}


3. 建立和user对应的映射文件****user.xml

在映射文件中创建sql语句。另外namespace=”user“,这里user是在mybatisconfig.xml配置文件定义了别名,当然也可以完整路径:namespace=”com.su.domain.User

mybatisconfig.xml




<configuration>
    
    <typeAliases>
        
        
        
        <package name="com.su.domain"/>
    typeAliases>

    
    <mappers>
        <mapper resource="com/su/domain/User.xml"/>
        <package name="com.su.mapper"/>
    mappers>





configuration>


user.xml




<mapper namespace="user">
    
    <select id="findNameCount" resultType="java.lang.Integer" parameterType="user">
        select count(*) from userTable where userName like '%${userName}%'
    select>

    
    <select id="findAllUser" resultType="user">
        select * from userTable
    select>

    
    <select id="findUserByPageName" parameterType="user" resultType="user">
        select * from userTable where userName like '%${userName}%'
    select>

mapper>


4. 创建UserDao

public interface UserDao {
    public Page findUserByPageName(int currentPage, User user);  //根据条件分页查询
}


*5. 创建UserDaoImpl
这个是最最最重要的代码,有了这,以后的分页就不愁了

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
     
    @Override
    public Page findUserByPageName(int currentPage, User user) {
        Page page = new Page();
        SqlSession sqlSession = this.getSqlSession();    //得到session
        int count = sqlSession.selectOne("user.findNameCount",user);    //根据条件查询记录数
        System.out.println("******总记录数:"+count);
        page.setTatalNums(count);       //总记录数
        int totalPages = (page.getTatalNums() % page.PAGESIZE) == 0?
                page.getTatalNums() / page.PAGESIZE : (page.getTatalNums() / page.PAGESIZE)+1;
        System.out.println("******总页数:"+totalPages);
        page.setTotalPages(totalPages);     //总页数
        if(currentPage < 1 || currentPage == 0){
            currentPage = 1;
        }else if(currentPage > totalPages){
            currentPage = totalPages;
        }
        System.out.println("******当前页:"+currentPage);
        page.setCurrentPage(currentPage);   //当前页
        int firstResult = (currentPage-1) * page.PAGESIZE;  //起始行
        page.setFirstResult(firstResult);   

        // RowBounds(offset,limit)   offset起始行 ,limit是当前页显示多少条数据
        RowBounds rowBounds = new RowBounds(page.getFirstResult(), page.PAGESIZE); 

        //查询记录
        List list = sqlSession.selectList("user.findUserByPageName", user,rowBounds);

        page.setList(list);

        return page;
    }


}


6. 创建UserService,UserServiceImpl

public interface UserService {
    public Page findUserByPageName(int currentPage, User user);  //根据条件分页查询
}


public class UserServiceImpl  implements UserService {
     
    @Autowired
    private UserDao userDao;

    @Override
    public Page findUserByPageName(int currentPage, User user) {

        return userDao.findUserByPageName(currentPage, user);
    }

}


7.这里创建控制器UserController,Jsp页面先访问控制器然后在通过控制器去调用其他的方法,最后再把结果解析由jsp页面显示

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("findUserByPageName.action")
    public ModelAndView findUserByPageName(Integer currentPage,User user,ModelAndView mav,HttpServletRequest request){

        System.out.println("in UserController method findUserByPageName()");

        if(user != null){
            System.out.println("搜索名:"+user.getUserName());
        }

         //检索条件,放到request中,在jsp页面回显搜索条件
        request.setAttribute("name", user.getUserName());

        Page page = userService.findUserByPageName(currentPage, user);

        System.out.println(page.getCurrentPage());

        request.setAttribute("page", page);

        mav.setViewName("jsp/user/userListTwo.jsp");

        return mav;
    }


写到这,分页显示就差不多完成了最后我们来看一下jsp页面吧

8. jsp页面主要来展示页面数据

<%@ page language="java" contentType="text/html; charset=UTF-8" import="com.su.util.*"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="f" %>

<html>
<head>
    <title>人事管理系统 ——用户管理title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <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 href="${pageContext.request.contextPath}/css/css.css" type="text/css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/ligerUI/skins/Aqua/css/ligerui-dialog.css"/>
    <link href="${pageContext.request.contextPath}/js/ligerUI/skins/ligerui-icons.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.0.js">script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-migrate-1.2.1.js">script>
    <script src="${pageContext.request.contextPath}/js/ligerUI/js/core/base.js" type="text/javascript">script>
    <script src="${pageContext.request.contextPath}/js/ligerUI/js/plugins/ligerDrag.js" type="text/javascript">script> 
    <script src="${pageContext.request.contextPath}/js/ligerUI/js/plugins/ligerDialog.js" type="text/javascript">script>
    <script src="${pageContext.request.contextPath}/js/ligerUI/js/plugins/ligerResizable.jss" type="text/javascript">script>
    <link href="${pageContext.request.contextPath}/css/pager.css" type="text/css" rel="stylesheet" />

    <script type="text/javascript">
    function one(frm,num){
       
        frm.currentPage.value=num;
        frm.submit();
    }
    function jump_to(frm,pageNo){
      
        var reg=/^\d+$/;
        if(!reg.test(pageNo)){
            alert("请输入正确数字");
        }else{
            one(frm,pageNo);
        }
    }



        $(function(){
      
           /** 获取上一次选中的部门数据 */
           var boxs  = $("input[type='checkbox'][id^='box_']");

          /** 给数据行绑定鼠标覆盖以及鼠标移开事件  */
            $("tr[id^='data_']").hover(function(){
      
                $(this).css("backgroundColor","#eeccff");
            },function(){
      
                $(this).css("backgroundColor","#ffffff");
            })


           /** 删除员工绑定点击事件 */
           $("#delete").click(function(){
      
               /** 获取到用户选中的复选框  */
               var checkedBoxs = boxs.filter(":checked");
               if(checkedBoxs.length < 1){
                   $.ligerDialog.error("请选择一个需要删除的用户!");
               }else{
                   /** 得到用户选中的所有的需要删除的ids */
                   var ids = checkedBoxs.map(function(){
      
                       return this.value;
                   })
                   //alert("删除:"+ids.get());
                   $.ligerDialog.confirm("确认要删除吗?","删除用户",function(r){
      
                       if(r){

                           // 发送请求
                           window.location = "${pageContext.request.contextPath}/removeUser.action?ids=" + ids.get();
                       }
                   });
               }
           })
        })
    script>
head>
<body>

    

    <table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr><td height="10">td>tr>
      <tr>
        <td width="15" height="32"><img src="${pageContext.request.contextPath}/images/main_locleft.gif" width="15" height="32">td>
        <td class="main_locbg font2"><img src="${pageContext.request.contextPath}/images/pointer.gif">   当前位置:用户管理 > 用户查询td>
        <td width="15" height="32"><img src="${pageContext.request.contextPath}/images/main_locright.gif" width="15" height="32">td>
      tr>
    table>

    <form name="empform" method="post" id="empform" action="${pageContext.request.contextPath}/findUserByPageName.action">
    <table width="100%" height="90%" border="0" cellpadding="5" cellspacing="0" class="main_tabbor">
      
      <tr valign="top">
        <td height="30">
          <table width="100%" border="0" cellpadding="0" cellspacing="10" class="main_tab">
            <tr>
              <td class="fftd">
                用户信息如下:

                    <table width="100%" border="0" cellpadding="0" cellspacing="0">
                      <tr>
                        <td class="font3">
                            用户名:<input type="text" name="userName" value="${requestScope.name }">
                            <input type="hidden" name="currentPage" value="1">
                                
                             <input type="submit" value="搜索"/>  
                            <input id="delete" type="button" value="删除"/>
                        td>
                      tr>
                    table>

              td>
            tr>
          table>
        td>
      tr>

      
      <tr valign="top">
        <td height="20">
          <table width="100%" border="1" cellpadding="5" cellspacing="0" style="border:#c2c6cc 1px solid; border-collapse:collapse;">
            <tr class="main_trbg_tit" align="center">
              <td><input type="checkbox" name="checkAll" id="checkAll">td>
              <td>登录名td>
              <td>密码td>
              <td>用户名td>
              <td>状态td>
              <td>创建时间td>
              <td align="center">操作td>
            tr>
            <c:forEach items="${requestScope.page.list}" var="user" varStatus="stat">
                <tr id="data_${stat.index}" align="center" class="main_trbg" onMouseOver="move(this);" onMouseOut="out(this);">
                    <td><input type="checkbox" id="box_${stat.index}" value="${user.userId}">td>
                     <td>${user.loginName }td>
                      <td>${user.loginPwd }td>
                      <td>${user.userName }td>
                      <td>${user.userStatus }td>
                      <td><f:formatDate value="${user.userCreateDate}" 
                                type="date" dateStyle="long"/>td>
                     <td align="center" width="40px;"><a href="${pageContext.request.contextPath}/updateUser.action?flag=1&userId=${user.userId}">
                            <img title="修改" src="${pageContext.request.contextPath}/images/update.gif"/>a>
                      td>
                tr>
            c:forEach>
          table>
        td>
      tr>
      
       <tr valign="top"><td align="center" class="font3">



        <% Page pageOne = (Page)request.getAttribute("page"); %>
        <% if(pageOne!=null) {
     for(int i=1;i<=pageOne.getTotalPages();i++){ %>
            <a href="javascript:one(document.forms[0],<%=i%>)"><font size="3px"><%=i%> font>a>
        <% }} %>

        <br>
        搜索结果共<font style="color:red">${page.tatalNums }font>条 当前页${page.currentPage}/共${page.totalPages}页
        <span>跳转至span><input type="text" name="inputPage" id="inputPage" value="${page.currentPage}" style="width:30px;text-align:center;"/><input type="button" onclick="javascript:jump_to(document.forms[0],document.getElementById('inputPage').value)" value="GO"/>

      td>tr>
    table>
    form>
    <div style="height:10px;">div>
body>
html>


分页功能显示已完成,供以后复习参考


Author:su1573

你可能感兴趣的:(SSH学习之路,ssm,分页)