spring系列(十三):SSM整合四_pagehelper5.0分页

环境:jdk1.7    spring3.2.2    struts2.3.15   mybatis3.2.8  druid1.0.9.jar   pagehelper-5.0.2.jar    jsqlparser-0.9.5.jar

pagehelper是目前最好用的mybatis分页插件

在我的博文mybatis系列中讲解了pagehelper的使用,这里我们来讲解该插件和spring的结合

所需要的包



目录结构


关键代码

==============spring核心配置文件context.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	                    http://www.springframework.org/schema/beans/spring-beans-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/tx
	                    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!-- 导入其它sping配置文件 -->
	<import resource="classpath:configs/spring/context-*.xml"/>
	<!-- durid连接池配置start -->
	<bean id="duridConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="locations">
		    <list>
				<value>classpath:configs/druid.properties</value>
			</list>
		</property>
    </bean>
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" 
		init-method="init" destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="filters" value="${filters}" />
		<property name="initialSize" value="${initialSize}" />
		<property name="maxActive" value="${maxActive}" />
		<property name="minIdle" value="${minIdle}" />
		<property name="maxWait" value="${maxWait}" />
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testWhileIdle" value="${testWhileIdle}" />
		<property name="testOnBorrow" value="${testOnBorrow}" />
		<property name="testOnReturn" value="${testOnReturn}" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}" />
		<property name="removeAbandoned" value="${removeAbandoned}" />
		<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
		<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
		<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
	</bean>
    <!-- durid连接池配置end -->
    
    <!-- spring整合mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="druidDataSource"></property>
		<property name="configLocation">
			<value>classpath:configs/mybatis-config.xml</value>
		</property>
		<property name="mapperLocations">
			<list>
				<value>classpath:configs/mappers/*.xml</value>
			</list>
		</property>
		<property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
	</bean>
	<bean id="sqlTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
	</bean>
	
	<!-- 事务配置start -->
	<bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="druidDataSource"></property>
	</bean>
	
	<tx:advice id="txAdvise" transaction-manager="txManger">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="search*" read-only="true"/>
			<tx:method name="load*" read-only="true"/>
			<tx:method name="query*" read-only="true"/>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="modify*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="del*" propagation="REQUIRED"/>
			<tx:method name="do*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:pointcut id="mycut" expression="execution(* com.obtk.biz.*.*(..))"/>
		<aop:advisor advice-ref="txAdvise" pointcut-ref="mycut"/>
	</aop:config>
	<!-- 事务配置end -->
</beans>
请关注spring整合mybatis部分

分页操作sql语句

<!-- 分页操作 -->
	<select id="selectByPage" parameterType="PageEntity" resultMap="stuJoinDept">
		select * from student s inner join department d
		on s.deptIdd=d.deptId
		where 1=1
		<if test="stuName!=null">
			and s.stuName like CONCAT('%',#{stuName},'%')
		</if>
		<if test="gender!=null">
			and s.gender = #{gender}
		</if>
		<if test="deptName!=null">
			and d.departName =#{deptName}
		</if>
		order by s.age desc
	</select>
=========额外的分页实体类PageEntity.java================

package com.obtk.entitys;

import java.io.Serializable;

public class PageEntity implements Serializable{
	
	private static final long serialVersionUID = -3179165911044543465L;
	
	private Integer pageNo=1;      //当前页码
	private Integer pageSize=3;    //每页显示多少条 
	private String stuName;     //搜索关键字
	private String gender;  //根据性别搜
	private String deptName;   //根据部门名称
	
	public PageEntity() {
	}
	public Integer getPageNo() {
		return pageNo;
	}
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}
	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getStuName() {
		return stuName;
	}
	
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	public String getDeptName() {
		return deptName;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
	
}
=============dao实现类StudentDaoImpl.java==================

package com.obtk.dao.stu;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.obtk.entitys.PageEntity;
import com.obtk.entitys.StudentEntity;

public class StudentDaoImpl implements IStudentDao{
	
	private SqlSessionTemplate sqlTemplate;
	
	public void setSqlTemplate(SqlSessionTemplate sqlTemplate) {
		this.sqlTemplate = sqlTemplate;
	}
	
	public StudentEntity loadOne(Integer stuId) {
		StudentEntity stu = sqlTemplate.selectOne("stu.selectById", stuId);
		return stu;
	}
	
	public PageInfo<StudentEntity> queryByPage(PageEntity thePage) {
		List<StudentEntity> stuList=null;
		PageHelper.startPage(thePage.getPageNo(), thePage.getPageSize());
		stuList=sqlTemplate.selectList("stu.selectByPage", thePage);
		PageInfo<StudentEntity> pageInfo=new PageInfo<StudentEntity>(stuList);
		return pageInfo;
	}
	
}

==================业务层代码StudentBiz.java=====================

package com.obtk.biz;


import com.github.pagehelper.PageInfo;
import com.obtk.dao.stu.IStudentDao;
import com.obtk.entitys.PageEntity;
import com.obtk.entitys.StudentEntity;

public class StudentBiz {
	private IStudentDao stuDao;
	
	public void setStuDao(IStudentDao stuDao) {
		this.stuDao = stuDao;
	}
	
	public StudentEntity loadOne(Integer stuId) {
		return stuDao.loadOne(stuId);
	}
	
	public PageInfo<StudentEntity> queryByPage(PageEntity thePage){
		return stuDao.queryByPage(thePage);
	}
}
================分页的action代码================

package com.obtk.actions.stu;

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

import com.github.pagehelper.PageInfo;
import com.obtk.biz.StudentBiz;
import com.obtk.entitys.PageEntity;
import com.obtk.entitys.StudentEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class StudentPageAction extends ActionSupport{
	private String stuName;
	private String gender;
	private String deptName;
	private String pageNo;
	private String pageSize;
	
	private StudentBiz stuBiz;
	
	public void setStuBiz(StudentBiz stuBiz) {
		this.stuBiz = stuBiz;
	}
	
	
	public String execute() throws Exception {
		//自己定义的分页参数,保存综合查询的表单参数
		PageEntity myPage=new PageEntity(); 
	    if(pageNo!=null){
	    	int myPageNo=Integer.parseInt(pageNo);
	    	myPage.setPageNo(myPageNo);
	    }
	    if(pageSize!=null){
	    	int myPageSize=Integer.parseInt(pageSize);
	    	myPage.setPageSize(myPageSize);
	    }
	    if(stuName!=null){
	    	stuName=new String(stuName.getBytes("iso-8859-1"),"utf-8");
	    	myPage.setStuName(stuName);
	    }
	    if(gender!=null){
	    	gender=new String(gender.getBytes("iso-8859-1"),"utf-8");
	    	myPage.setGender(gender);
	    }
	    if(deptName!=null){
	    	deptName=new String(deptName.getBytes("iso-8859-1"),"utf-8");
	    	myPage.setDeptName(deptName);
	    }
	    PageInfo<StudentEntity> pageInfo=stuBiz.queryByPage(myPage);
	    //当前页是第一页时,上一页也是第一页
	    if(pageInfo.getPageNum()==1){
	    	pageInfo.setPrePage(1);
	    }
	    //当前也是最后一页时,下一页也是最后一页
	    if(pageInfo.getPageNum()==pageInfo.getPages()){
	    	pageInfo.setNextPage(pageInfo.getPages());
	    }
		//第一次进来就是第一页数据
		List<StudentEntity> stuList=pageInfo.getList();
		ActionContext ac=ActionContext.getContext();
		Map request=(Map)ac.get("request");
		if(stuList!=null){
			//分页实体对象
			request.put("myPage",myPage);
			//尽量用request对象保存数据
			request.put("stuList",stuList);
			request.put("pageInfo", pageInfo);
			return this.SUCCESS;
		}else{
			return this.ERROR;
		}
	}
	
	
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}


	public String getPageNo() {
		return pageNo;
	}


	public void setPageNo(String pageNo) {
		this.pageNo = pageNo;
	}


	public String getPageSize() {
		return pageSize;
	}


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

}
==================分页页面======================

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.obtk.entitys.*"%> 
<c:set var="path" value="${pageContext.request.contextPath}"></c:set>
<c:set var="scheme" value="${pageContext.request.scheme}"></c:set>
<c:set var="serverName" value="${pageContext.request.serverName}"></c:set>
<c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set>
<c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${path}/"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> 
  <head>
    <!-- 设定参考路径 -->
    <base href="${basePath }">
    <title>第一个页面</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">  
<script type="text/javascript">
	function changePage(){
		var sizeStrTag=document.getElementsByName("theSize")[0];
		var sizeStr=sizeStrTag.value;
		window.location="QueryStuPage.php?pageNo=1&pageSize="+sizeStr;
	}
</script>  
  </head>
<body>

<h2>欢迎您:${sessionScope.userName}  <a href="Quit.php">退出</a></h2>

<h2>显示学生的数据 </h2>
<form action="QueryStuPage.php" method="get">
	<p><input type="text" name="stuName" value="${myPage.stuName}"/> 
		<input type="submit" value="搜索"/>
	</p>
</form>
<c:if test="${not empty stuList}">

<table border="1px">
	<tr><td>编号</td><td>名称</td><td>性别</td><td>年龄</td><td>部门</td><td>操作</td></tr>
   <c:forEach items="${stuList}" var="stu"> 
   	 <tr><td>${stu.stuId}</td><td>${stu.stuName}</td>
   	     <td>${stu.gender}</td>
   	     <td>${stu.age}</td><td>${stu.dept.departName}</td>
   	     <td><a href="DeleteStu.php?stuId=${stu.stuId}">删除</a> 
   	         <a href="QueryOne.php?stuId=${stu.stuId}">修改</a></td></tr>
   </c:forEach>
</table>
<p>当前页码:${pageInfo.pageNum}/${pageInfo.pages}   
    <a href="QueryStuPage.php?pageNo=1&pageSize=${pageInfo.pageSize}&keyStr=${myPage.stuName}">首页</a> 
    <a href="QueryStuPage.php?pageNo=${pageInfo.pages}&pageSize=${pageInfo.pageSize}&keyStr=${myPage.stuName}">尾页</a> 
    <a href="QueryStuPage.php?pageNo=${pageInfo.prePage}&pageSize=${pageInfo.pageSize}&keyStr=${myPage.stuName}">上一页</a> 
    <a href="QueryStuPage.php?pageNo=${pageInfo.nextPage}&pageSize=${pageInfo.pageSize}&keyStr=${myPage.stuName}">下一页</a>
     每页显示多少条<select name="theSize" οnchange="changePage();">
    	<option value="3"
    		<c:if test="${pageInfo.pageSize eq 3}">selected="selected"</c:if>
    	    >3</option>
    	<option value="5" 
    		<c:if test="${pageInfo.pageSize eq 5}">
    	    	selected="selected"
    	    </c:if>
    	   >5</option>
    	<option value="8"
    	    <c:if test="${pageInfo.pageSize eq 8}">
    	    	selected="selected"
    	    </c:if>
    	   >8</option>
    </select>
</p>
</c:if>
</body>
</html>

效果图


如果帮到了您,请点个赞吧!













  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值