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

SSM实现分页查询Demo

程序员文章站 2024-03-14 20:12:23
...

最终效果:

SSM实现分页查询Demo

1、数据访问层

1、数据库建表:

DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
	id INT NOT NULL AUTO_INCREMENT,
	userName VARCHAR(40),
	password VARCHAR(100),
	email VARCHAR(40),
	phone VARCHAR(40),
	roleName VARCHAR(40),
	PRIMARY KEY(id)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2、封装实体类:

/**
 * 用户实体类----对应数据表tb_user
 */
@Data
public class User {

    private Integer id;
    private String username;
    private String password;
    private String email;
    private String phone;
    private String rolename;

    public User() {
    }

   public User(String username, String password, String email, String phone, String rolename) {
      super();
      this.username = username;
      this.password = password;
      this.email = email;
      this.phone = phone;
      this.rolename = rolename;
   }
}

3、Mapper配置文件:

<?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.hh.dao.UserDao">

   <resultMap id="BaseResultMap" type="com.hh.entity.User">
      <id column="id" property="id" jdbcType="INTEGER" />
      <result column="userName" property="username" jdbcType="VARCHAR" />
      <result column="password" property="password" jdbcType="VARCHAR" />
      <result column="email" property="email" jdbcType="VARCHAR" />
      <result column="phone" property="phone" jdbcType="VARCHAR" />
      <result column="roleName" property="rolename" jdbcType="VARCHAR" />
   </resultMap>

   <sql id="Base_Column_List">
      id, userName, password, email, phone, roleName
   </sql>

   <!--用户登录 -->
   <select id="loginByUserNameAndPassword"  resultMap="BaseResultMap" parameterType="com.hh.entity.User">
      select <include refid="Base_Column_List"/> from tb_user
       where userName = #{username} and password = #{password}
   </select>
   
   <!-- 根据分页数据start 和size查询数据 -->
   <select id="findByPage" parameterType="Map" resultMap="BaseResultMap">
      select <include refid="Base_Column_List"/> from tb_user
      <if test="start!=null and size!=null">
         limit #{start},#{size}
      </if>
   </select>

   <!--查询所有用户数据 -->
   <select id="selectUserList" resultType="com.hh.entity.User">
      select <include refid="Base_Column_List" /> from tb_user
   </select>

   <!-- 查询用户记录总数 -->
   <select id="selectCount" resultType="int">
      select count(*) from tb_user
   </select>

</mapper>

4、封装与分页相关的数据:

/**
 * 分页实体类:存储当前页所有分页相关的数据
 *
 * 分页的三个基本属性:
 *  1、每页几条记录pageSize,可以有默认值
 *  2、当前第几页currPage,可以有默认值
 *  3、总记录数totalCount,不可以有默认值,必须从数据库中查到
 */

@Data
@NoArgsConstructor
public class PageBean<User> {
    /**
     * 当前页面显示的数据
     */
    private List<User> lists;

    /**
     * 1、当前第几页
     */
    private int currPage;

    /**
     * 2、每页显示几条记录
     */
    private int pageSize;

    /**
     * 3、总共有多少条记录
     */
    private int totalCount;

    /**
     * 总页数:这个不是基本属性,可以通过计算得出:totalCount/pageSize
     */
    private int totalPage;
}

2、业务层

/**
 * User类业务层实现类
 */
@Service
public class UserService {

	@Resource
	private UserDao userDao;

	public User loginByUserNameAndPassword(User record) {
		return userDao.loginByUserNameAndPassword(record);
	}

	public List<User> selectUserList() {
		return userDao.selectUserList();
	}

	public int selectCount() {
		return userDao.selectCount();
	}

	public PageBean<User> findByPage(int currentPage) {

		HashMap<String,Object> map = new HashMap<>();
		PageBean<User> pageBean = new PageBean<>();

		//在业务层要做的就是给PageBean的所有属性赋值

		//1、当前页数
        pageBean.setCurrPage(currentPage);

		//2、每页显示的数据
		int pageSize=5;
		pageBean.setPageSize(pageSize);

		//3、总记录数
		int totalCount = userDao.selectCount();
		pageBean.setTotalCount(totalCount);

		//4、根据总记录数和每页显示的记录数计算总页数
		double tc = totalCount;
        Double num =Math.ceil(tc/pageSize);//向上取整
        pageBean.setTotalPage(num.intValue());


        //每页的起始编号为(id编号):(currentPage-1)*pageSize
		map.put("start",(currentPage-1)*pageSize);
		//每页查询的记录数
		map.put("size", pageBean.getPageSize());

		//5、从数据库中查询出每页显示的数据
		List<User> lists = userDao.findByPage(map);
		pageBean.setLists(lists);

		return pageBean;
	}
}

3、表现层

@Controller
public class UserController {

   @Resource
   private UserService userService;

   /**
    * 分页查询
    */
   @RequestMapping("/main")
   public String main(@RequestParam(value="currentPage", defaultValue="1", required=false)int currentPage,
                  Model model){
      //回显分页数据
      model.addAttribute("pagemsg", userService.findByPage(currentPage));
      return "main";
   }

   /**
    * 用户登录
    */
   @RequestMapping("/login")
   public String login(@RequestParam("userName")String userName,
         @RequestParam("password")String password,Model model) throws Exception{
      User user = new User();
      user.setUsername(userName);
      user.setPassword(password);
      User userresult = userService.loginByUserNameAndPassword(user);
      if(userresult!=null){
         //登录成功
         List<User> lists = userService.selectUserList();
         //回显用户信息
         model.addAttribute("userLists", lists);
         model.addAttribute("currentUser", userresult.getUsername());
         return "redirect:main";
      }
      return "登录账号或密码错误,请检查.......";
   }
}

前台页面JSP:

<body>
   欢迎你:${currentUser}
   <br>
   <hr>
   <c:if test="${empty requestScope.pagemsg}">
      没有任何用户信息!
   </c:if>
   <c:if test="${!empty requestScope.pagemsg}">
      <table border="1" cellpadding="10" cellspacing="0" class="table1">
      <thead>
         <tr>
            <td>编号</td>
            <td>用户名</td>
            <td>密码</td>
            <td>邮件</td>
            <td>联系电话</td>
            <td>职位</td>
            <td>Edit</td>
            <td>Delete</td>
         </tr>
         </thead>
         <c:forEach items="${requestScope.pagemsg.lists}" var="u">
            <tr>
               <th>${u.id }</th>
               <th>${u.username }</th>
               <th>${u.password }</th>
               <th>${u.email }</th>
               <th>${u.phone }</th>
               <th>${u.rolename }</th>
               <th>Edit</th>
               <th>Delete</th>
            </tr>
         </c:forEach>      
      </table>   
   </c:if>

<table  border="0" cellspacing="0" cellpadding="0"  width="900px">
<tr>

<td class="td2">
   <span>第${requestScope.pagemsg.currPage }/ ${requestScope.pagemsg.totalPage}页</span>&nbsp;&nbsp;
   <span>总记录数:${requestScope.pagemsg.totalCount }&nbsp;&nbsp;每页显示:${requestScope.pagemsg.pageSize}</span>&nbsp;&nbsp;
   <span>
       <c:if test="${requestScope.pagemsg.currPage != 1}">
           <a href="${pageContext.request.contextPath }/main?currentPage=1">[首页]</a>&nbsp;&nbsp;
           <a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.currPage-1}">[上一页]</a>&nbsp;&nbsp;
       </c:if>
       
       <c:if test="${requestScope.pagemsg.currPage != requestScope.pagemsg.totalPage}">
           <a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.currPage+1}">[下一页]</a>&nbsp;&nbsp;
           <a href="${pageContext.request.contextPath }/main?currentPage=${requestScope.pagemsg.totalPage}">[尾页]</a>&nbsp;&nbsp;
       </c:if>
   </span>
</td>
</tr>
</table>
</body>

页面效果展示:
SSM实现分页查询Demo

相关标签: SSM整合