欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM框架分页查询

程序员文章站 2024-01-15 23:56:34
...

展示分页效果图:
SSM框架分页查询
创建数据库 system_user
SSM框架分页查询

CREATE TABLE `system_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `username` varchar(40) DEFAULT NULL COMMENT '账号',
  `pwd` varchar(40) DEFAULT NULL COMMENT '密码',
  `create_date` datetime DEFAULT NULL COMMENT '创建时间',
  `use_status` varchar(2) DEFAULT '1' COMMENT '启用状态:1启用,0禁用',
  `is_admin` varchar(2) DEFAULT '0' COMMENT '1超级管理员,0普通管理员',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8

创建class类 如图:
SSM框架分页查询

po

package com.zx.po;

import java.io.Serializable;
import java.util.Date;

/**
 * system_user
 * @author 
 */
public class SystemUser implements Serializable {
    /**
     * 主键
     */
    private Long id;

    /**
     * 账号
     */
    private String username;

    /**
     * 密码
     */
    private String pwd;

    /**
     * 创建时间
     */
    private Date createDate;

    /**
     * 启用状态:1启用,0禁用
     */
    private String useStatus;

    /**
     * 1超级管理员,0普通管理员
     */
    private String isAdmin;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public String getUseStatus() {
        return useStatus;
    }

    public void setUseStatus(String useStatus) {
        this.useStatus = useStatus;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        SystemUser other = (SystemUser) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
            && (this.getPwd() == null ? other.getPwd() == null : this.getPwd().equals(other.getPwd()))
            && (this.getCreateDate() == null ? other.getCreateDate() == null : this.getCreateDate().equals(other.getCreateDate()))
            && (this.getUseStatus() == null ? other.getUseStatus() == null : this.getUseStatus().equals(other.getUseStatus()))
            && (this.getIsAdmin() == null ? other.getIsAdmin() == null : this.getIsAdmin().equals(other.getIsAdmin()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
        result = prime * result + ((getPwd() == null) ? 0 : getPwd().hashCode());
        result = prime * result + ((getCreateDate() == null) ? 0 : getCreateDate().hashCode());
        result = prime * result + ((getUseStatus() == null) ? 0 : getUseStatus().hashCode());
        result = prime * result + ((getIsAdmin() == null) ? 0 : getIsAdmin().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", username=").append(username);
        sb.append(", pwd=").append(pwd);
        sb.append(", createDate=").append(createDate);
        sb.append(", useStatus=").append(useStatus);
        sb.append(", isAdmin=").append(isAdmin);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

Dao

package com.zx.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zx.po.OneMenu;
import com.zx.po.SystemUser;

/**
 * SystemUserDAO继承基类
 */
public interface SystemUserDAO {
    /**
     * 用户信息查询--查询所有系统用户信息 分页
     */
    List<SystemUser> selectAllSystemUser(HashMap<String,Object> map);
    
    /**
     * 分页数量
     * @return
     */
    int selectCount(); 
}

mapping

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zx.dao.SystemUserDAO">
  <resultMap id="BaseResultMap" type="com.zx.po.SystemUser">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="pwd" jdbcType="VARCHAR" property="pwd" />
    <result column="create_date" jdbcType="TIMESTAMP" property="createDate" />
    <result column="use_status" jdbcType="VARCHAR" property="useStatus" />
    <result column="is_admin" jdbcType="VARCHAR" property="isAdmin" />
  </resultMap>
  <sql id="Base_Column_List">
    id, username, pwd, create_date, use_status, is_admin
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from system_user
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from system_user
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.zx.po.SystemUser">
    insert into system_user (id, username, pwd, 
      create_date, use_status, is_admin
      )
    values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR}, 
      #{createDate,jdbcType=TIMESTAMP}, #{useStatus,jdbcType=VARCHAR}, #{isAdmin,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.zx.po.SystemUser">
    insert into system_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="pwd != null">
        pwd,
      </if>
      <if test="createDate != null">
        create_date,
      </if>
      <if test="useStatus != null">
        use_status,
      </if>
      <if test="isAdmin != null">
        is_admin,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="pwd != null">
        #{pwd,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null">
        #{createDate,jdbcType=TIMESTAMP},
      </if>
      <if test="useStatus != null">
        #{useStatus,jdbcType=VARCHAR},
      </if>
      <if test="isAdmin != null">
        #{isAdmin,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zx.po.SystemUser">
    update system_user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="pwd != null">
        pwd = #{pwd,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null">
        create_date = #{createDate,jdbcType=TIMESTAMP},
      </if>
      <if test="useStatus != null">
        use_status = #{useStatus,jdbcType=VARCHAR},
      </if>
      <if test="isAdmin != null">
        is_admin = #{isAdmin,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zx.po.SystemUser">
    update system_user
    set username = #{username,jdbcType=VARCHAR},
      pwd = #{pwd,jdbcType=VARCHAR},
      create_date = #{createDate,jdbcType=TIMESTAMP},
      use_status = #{useStatus,jdbcType=VARCHAR},
      is_admin = #{isAdmin,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>


	<!-- 用户信息查询     查询所有系统用户信息 -->
	<select id="selectAllSystemUser" resultMap="BaseResultMap">
		SELECT * FROM SYSTEM_USER
		<if test="start!=null and size!=null">
			limit #{start},#{size}
		</if>
	</select>
	
	<!-- 查询用户记录总数 -->
	<select id="selectCount" resultType="int">
		select count(*) from SYSTEM_USER
	</select>
	
	
</mapper>

utils

package com.zx.utils;
/**
 * 分页工具
 * @author Administrator
 *
 * @param <T>
 */
import java.util.List;

public class PageBean<T> {
	private int currPage;//当前页数
    private int pageSize;//每页显示的记录数
    private int totalCount;//总记录数
    private int totalPage;//总页数
    private List<T> lists;//每页的显示的数据
	
	public PageBean() {
		super();
	}
 
	public int getCurrPage() {
		return currPage;
	}
 
	public void setCurrPage(int currPage) {
		this.currPage = currPage;
	}
 
	public int getPageSize() {
		return pageSize;
	}
 
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
 
	public int getTotalCount() {
		return totalCount;
	}
 
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
 
	public int getTotalPage() {
		return totalPage;
	}
 
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
 
	public List<T> getLists() {
		return lists;
	}
 
	public void setLists(List<T> lists) {
		this.lists = lists;
	}
}

Service

package com.zx.service;

import java.util.List;


import java.util.Map;

import com.zx.po.OneMenu;
import com.zx.po.SystemUser;
import com.zx.utils.PageBean;
import com.zx.vo.SystemUserVo;

public interface SystemUserService {

    /**
     * 用户信息查询--查询所有系统用户信息 分页
     * @param pageNum
     * @param pageSize
     * @return
     */
      PageBean<SystemUser> findSystemUserByLimit(int currentPage);
  
    
}

ServiceImpl

package com.zx.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.zx.dao.SystemUserDAO;
import com.zx.po.OneMenu;
import com.zx.po.SystemUser;
import com.zx.service.SystemUserService;
import com.zx.utils.MD5Tool;
import com.zx.utils.PageBean;
import com.zx.vo.SystemUserVo;
@Service
public class SystemUserServiceImpl implements SystemUserService{

	@Autowired
	private SystemUserDAO systemUserDAO;

	@Override
	public PageBean<SystemUser> findSystemUserByLimit(int currentPage) {
		HashMap<String,Object> map = new HashMap<String,Object>();
		PageBean<SystemUser> pageBean = new PageBean<SystemUser>();
		//封装当前页数
        pageBean.setCurrPage(currentPage);
        
        //每页显示的数据
  		int pageSize=11;
  		pageBean.setPageSize(pageSize);
        
  		//封装总记录数
		int totalCount = systemUserDAO.selectCount();
		pageBean.setTotalCount(totalCount);
		
		//封装总页数
		double tc = totalCount;
        Double num =Math.ceil(tc/pageSize);//向上取整
        pageBean.setTotalPage(num.intValue());
		
        map.put("start",(currentPage-1)*pageSize);
		map.put("size", pageBean.getPageSize());
		//封装每页显示的数据
		List<SystemUser> lists = systemUserDAO.selectAllSystemUser(map);
		pageBean.setLists(lists);

		return pageBean;
	}

}

Controller

package com.zx.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zx.po.OneMenu;
import com.zx.po.SystemUser;
import com.zx.service.SystemUserService;
import com.zx.vo.SystemUserVo;

@Controller
@RequestMapping("/SystemUser")
public class SystemUserController {

	@Autowired
	private SystemUserService systemUserService;
	/**
	 * 用户信息查询--查询所有系统用户信息
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
    @RequestMapping("/getSystemUserByLimit.do")
    public String getSystemUserByLimit(@RequestParam(value="currentPage",
			defaultValue="1",required=false) int currentPage,Model model) {
        model.addAttribute("pagemsg", systemUserService.findSystemUserByLimit(currentPage));//回显分页数据
        return "/user/showSystemUser";
    }

}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set  value="${pageContext.request.contextPath}"  scope="page"  var="ctx"></c:set>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<!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>
</head>
<link href="${ctx}/static/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${ctx}/static/js/jquery.js"></script>
<style type="text/css">
	.ones{
		
	}
	.two{
		margin-left: 10px
	}
	.one{
		color: #d7a372;
		font-size: 14px;
		display: inline;
		
		/* 不选中文字 */
		-moz-user-select: none; /*火狐*/
        -webkit-user-select: none; /*webkit浏览器*/
        -ms-user-select: none; /*IE10*/
        -khtml-user-select: none; /*早期浏览器*/
        -o-user-select: none; /* Opera*/
        user-select: none;
	}
	.three{
		float: right;
	}
	.threes{
		background-color: #F2BF74;
		font-size: 15px;
		padding: 3px;
		margin-top: 5px;
		border-radius: 5px;
	}
</style>
<script type="text/javascript">
$(document).ready(function(){
  $(".click").click(function(){
  $(".tip").fadeIn(200);
  });
  
  $(".tiptop a").click(function(){
  $(".tip").fadeOut(200);
});

  $(".sure").click(function(){
  $(".tip").fadeOut(100);
});

  $(".cancel").click(function(){
  $(".tip").fadeOut(100);
});

});
</script>
<body>
<div class="place"> <span>位置:</span>
  <ul class="placeul">
    <li><a href="main.html">系统用户管理</a></li>
    <li><a href="#">用户信息查询</a></li>
  </ul>
</div>
<div class="rightinfo">
  <div class="tools">
    <ul class="toolbar">
      <li class="click"><span><img src="${ctx}/static/images/t01.png" /></span>添加</li>
      <li class="click"><span><img src="${ctx}/static/images/t02.png" /></span>修改</li>
      <li><span><img src="${ctx}/static/images/t03.png" /></span>删除</li>
    </ul>
    
    <div class="toolbar1">
      <table>
        <form method="get" name="serch">
          <tr>
            <td class="zi"><span>选择分类:</span></td>
            <td><select>
                <option>用户名</option>
              </select></td>
            <td class="zi"><span>关键字:</span></td>
            <td><input type="text" placeholder="与分类关联"/></td>
            <td><input type="submit" value="查询" class="button"/></td>
          </tr>
        </form>
      </table>
    </div>
    
  </div>
  <table class="tablelist">
    <thead>
      <tr>
        <th>
        <input name="" type="checkbox" value="" checked="checked"/>
        </th>
        <th>编号</th>
        <th>用户名</th>
        <th>创建时间</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
		<c:forEach items="${requestScope.pagemsg.lists}" var="map" varStatus="num">
		      <tr>
		        <td><input name="" type="checkbox" value="" /></td>
		        <td>${num.count }</td>
		        <td>${map.username }</td>
		        <td><fmt:formatDate value="${map.createDate }" pattern="yyyy-MM-dd HH:mm:ss"/></td>
		        <td>${map.useStatus=='1'?'启动':'禁用' }</td>
		        <td>
		        	<c:choose>
		        		<c:when test="${map.isAdmin==1 }"><a href="javascript:void(0)" class="tablelink">无操作</a> </c:when>
		        		<c:otherwise>
		        			<a href="${ctx}/SystemUser/updateSystemUserStatus.do?userId=${map.id}&flag=${map.useStatus=='1'?'0':'1' }" class="tablelink">${map.useStatus=='1'?'禁用':'启用' }</a>
		        		</c:otherwise>
		        	</c:choose>
		        </td>
		      </tr>
		</c:forEach>    
    </tbody>
  </table>
  分页
  <table  border="0" cellspacing="0" cellpadding="0"  width="100%" height="35px">
	<tr>
		<td class="td2">
		   <span class="one ones">第${requestScope.pagemsg.currPage }/ ${requestScope.pagemsg.totalPage}</span>  
		   <span class="one two">&nbsp;${requestScope.pagemsg.totalCount }&nbsp;&nbsp;&nbsp;每页显示:${requestScope.pagemsg.pageSize}</span>  
			 <span class="one three">
			     <c:if test="${requestScope.pagemsg.currPage != 1}">
			         <a class="threes" href="${pageContext.request.contextPath }/SystemUser/getSystemUserByLimit.do?currentPage=1">首页</a>  
			         <a class="threes" href="${pageContext.request.contextPath }/SystemUser/getSystemUserByLimit.do?currentPage=${requestScope.pagemsg.currPage-1}">上一页</a>  
			     </c:if>
			     
			     <c:if test="${requestScope.pagemsg.currPage != requestScope.pagemsg.totalPage}">
			         <a class="threes" href="${pageContext.request.contextPath }/SystemUser/getSystemUserByLimit.do?currentPage=${requestScope.pagemsg.currPage+1}">下一页</a>  
			         <a class="threes" href="${pageContext.request.contextPath }/SystemUser/getSystemUserByLimit.do?currentPage=${requestScope.pagemsg.totalPage}">尾页</a>  
			     </c:if>
			 </span>
		</td>
	</tr>
	</table>
  
  
  
  
  <div class="tip">
    <div class="tiptop"><span>提示信息</span><a></a></div>
    <div class="tipinfo"> <span><img src="images/ticon.png" /></span>
      <div class="tipright">
        <p>是否确认对信息的修改 ?</p>
        <cite>如果是请点击确定按钮 ,否则请点取消。</cite> </div>
    </div>
    <div class="tipbtn">
      <input name="" type="button"  class="sure" value="确定" />
      &nbsp;
      <input name="" type="button"  class="cancel" value="取消" />
    </div>
  </div>
</div>
<script type="text/javascript">
	$('.tablelist tbody tr:odd').addClass('odd');
	</script>
</body>
</html>