Bootstrap

PageHelper分页实战(SSM整合)

步骤一:引入SSM相关的jar包,包列表如下;

 

 

 

步骤二:创建或修改配置文件,配置文件清单如下;

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config />
    <context:component-scan base-package="com.sunfreeter.service" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3666/pagetest?characterEncoding=UTF-8
            </value>

        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>root!@@123</value>
        </property>
    </bean>


    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/sunfreeter/mapperXml/*.xml" />
        <property name="typeAliasesPackage" value="com.sunfreeter.pojo" />
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            offsetAsPageNum=true
                            rowBoundsWithCount=true
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sunfreeter.mapper" />
    </bean>

</beans>

springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <context:annotation-config/>

    <context:component-scan base-package="com.sunfreeter.controller">
          <context:include-filter type="annotation" 
          expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven />

    <mvc:default-servlet-handler />


    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.sunfreeter=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

步骤三:创建业务相关的类及配置文件;

创建实体User

package com.sunfreeter.pojo;

public class User {
 private int id;
 private String name;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

创建Mapper文件

package com.sunfreeter.mapper;

import java.util.List;

import com.sunfreeter.pojo.User;


public interface UserMapper {
    public List<User> list();

}

创建映射文件

<?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.sunfreeter.mapper.UserMapper">
        <select id="list" resultType="com.sunfreeter.pojo.User">
            select * from  user      
        </select>
    </mapper>

创建服务接口及类

package com.sunfreeter.service;
import java.util.List;
import com.sunfreeter.pojo.User;
public interface UserService {
    List<User> list();
}

 

package com.sunfreeter.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sunfreeter.mapper.UserMapper;
import com.sunfreeter.pojo.User;
import com.sunfreeter.service.UserService;

@Service
public class UserServiceImpl  implements UserService{
    @Autowired
    UserMapper userMapper;
    public List<User> list(){
        return userMapper.list();
    }

}

创建控制器

package com.sunfreeter.controller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunfreeter.pojo.User;
import com.sunfreeter.service.UserService;

@Controller
@RequestMapping("")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("listUser")
    public String  listUser(@RequestParam(defaultValue="1",required=true,value="pageNo") Integer pageNo,ModelMap map){
        Integer pageSize=4;//每页显示记录数
        //分页查询
        PageHelper.startPage(pageNo, pageSize);
        List<User> userList = userService.list();//获取所有用户信息
        PageInfo<User> pageInfo=new PageInfo<User>(userList);
        map.addAttribute("pageInfo", pageInfo);
        return "listUser";
    }

}

步骤四:创建前台页面.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div style="width: 500px; margin: 0px auto; text-align: center">
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
        </tr>
        <c:forEach items="${pageInfo.list}" var="c" varStatus="st">
            <tr>
                <td>${c.id}</td>
                <td>${c.name}</td>
            </tr>
        </c:forEach>
    </table>
    <div style="text-align: center">
        <p>当前 ${pageInfo.pageNum }页,总${pageInfo.pages } 页,总
            ${pageInfo.total } 条记录
    </div>
    </p>
    <a href="?pageNo=${pageInfo.firstPage}">首页</a>
    <c:if test="${pageInfo.hasPreviousPage }">
        <a href="?pageNo=${pageInfo.pageNum-1}">上一页</a>
    </c:if>

    <c:if test="${pageInfo.hasNextPage }">
        <a href="?pageNo=${pageInfo.pageNum+1}">下一页</a>
    </c:if>

    <a href="?pageNo=${pageInfo.lastPage}">最后页</a>
</div>
</div>

        直到目前所有该有的文件我们都创建完了,细心的小伙伴可能已经发现了,我已经将分页一并贴出来了,那么,我们就开始看分页怎么处理,我们借助PageHelper工具包进行分页的实现,其实自己去写一个属于自己的分页也不是很难,但是在实战中我们要的是效率,所谓站在巨人的肩膀上才会看得更远嘛!

PageHelper分页的好处在于,代码比较简洁,好入手(感觉我是PageHelper的托!),可以让你把精力专注于业务上;

1、只需要引入pagehelper-5.1.0-beta2.jar和jsqlparser-1.0.jar;

2、配置文件applicationContext.xml的id="sqlSession"加上PageInterceptor插件就可以,特别是reasonable=true参数一定不能忘,它限制了超过最后一页和小于第一页传入的pageNo数,不加的话看查询日志就会发现limit 可能成为负数或者大于最大条数;

3、然后在控制器中传入pageNo参数;在进行数据库查询前加上

PageHelper.startPage(pageNo, pageSize);

在查询数据库完成后再加下面一句就可以了;

PageInfo<User> pageInfo=new PageInfo<User>(userList);

4、前端页面使用pageInfo相关参数就搞定!具体的参考我上面listUser.jsp贴出来的代码

是不是很简单?最后我们来一起看看效果

 

转载于:https://www.cnblogs.com/zhengjinsheng/p/11114303.html

;