首页 > 代码库 > struts2+spring+hibernate 实现分页

struts2+spring+hibernate 实现分页

在这里要感谢下这位博友发表的博文

http://www.blogjava.net/rongxh7/archive/2008/11/29/243456.html

通过对他代码的阅读,从而自己实现了网页分页功能,下面给大家分享下我的代码

1.entity实体类

我项目例子的实体类叫News

2.DAO接口的设计,定义一个NewsDAO接口,里面声明了两个方法:

public interface NewsDAO {        public int getAllRowCount(String hql);        public List<News> queryByPage(String hql, int offset, int pageSize);    }

3.DAO层接口的实现类NewsDAOImpl类,并实现接口的两个方法:

public class NewsDAOImpl implements NewsDAO{    //注解注入属性实例    @Resource(name="mySessionFactory_mysql")    private SessionFactory sessionFactory;     /**     * 通过hql语句得到数据库中记录总数     */    @Override    public int getAllRowCount(String hql) {        Session session=sessionFactory.openSession();        Transaction tx=null;        int allRows=0;                try{            tx=session.beginTransaction();            Query query=session.createQuery(hql);            allRows=query.getResultList().size();            tx.commit();        }catch (Exception e){             if(tx != null)                {                    tx.rollback();                }                             e.printStackTrace();        }finally{            if(session!=null){                session.close();                }        }                return allRows;    }         /**     * 使用hibernate提供的分页功能,得到分页显示的数据     */    @Override    public List<News> queryByPage(String hql, int offset, int pageSize) {                Session session=sessionFactory.openSession();        Transaction tx=null;        List<News> list=null;                try{            tx=session.beginTransaction();            Query query=session.createQuery(hql).setFirstResult(offset).setMaxResults(pageSize);            list=query.getResultList();            tx.commit();        }catch(Exception e){                        if(tx != null)            {                tx.rollback();            }                        e.printStackTrace();                    }finally{            if(session!=null){                session.close();                }                    }                return list;    }}

4.定义了一个PageBean(每一页所需要的内容都存放在这个PageBean里面),里面用来存放网页每一页显示的内容:

public class PageBean {    private List<News> list; //通过hql从数据库分页查询出来的list集合            private int allRows; //总记录数        private int totalPage; //总页数        private int currentPage; //当前页    public List<News> getList() {        return list;    }    public void setList(List<News> list) {        this.list = list;    }    public int getAllRows() {        return allRows;    }    public void setAllRows(int allRows) {        this.allRows = allRows;    }    public int getTotalPage() {        return totalPage;    }    public void setTotalPage(int totalPage) {        this.totalPage = totalPage;    }    public int getCurrentPage() {        return currentPage;    }    public void setCurrentPage(int currentPage) {        this.currentPage = currentPage;    }    /**     * 得到总页数     * @param pageSize 每页记录数     * @param allRows  总记录数     * @return 总页数     */        public int getTotalPages(int pageSize, int allRows){        int totalPage = (allRows % pageSize == 0)? (allRows / pageSize): (allRows / pageSize) + 1;                return totalPage;    }        /**     * 得到当前开始记录号     * @param pageSize 每页记录数     * @param currentPage 当前页     * @return     */    public int getCurrentPageOffset(int pageSize, int currentPage){        int offset = pageSize * (currentPage - 1);                return offset;    }        /**     * 得到当前页, 如果为0 则开始第一页,否则为当前页     * @param page     * @return     */    public int getCurPage(int page){        int currentPage = (page == 0)? 1: page;                return currentPage;    }}

5.Service层接口设计,定义一个NewsService接口,里面声明了一个方法,返回一个PageBean:

public interface NewsService {    public PageBean getPageBean(int pageSize,int page);}

6.Service层接口实现类NewsServiceImpl类,实现NewsService接口的方法:

public class NewsServiceImpl implements NewsService{        //注解注入属性实例    @Resource(name="myNewsDao")    private NewsDAO newsDao;    @Resource(name="myPageBean")    private PageBean pageBean;        /**     * pageSize为每页显示的记录数     * page为当前显示的网页     */        @Override    public PageBean getPageBean(int pageSize, int page) {        String hql="from News";                //总记录数        int allRows=newsDao.getAllRowCount(hql);                //总页数        int totalPage=pageBean.getTotalPages(pageSize,allRows);                //当前页        int currentPage=pageBean.getCurPage(page);                //锚点(从第几条数据开始查询)        int offset=pageBean.getCurrentPageOffset(pageSize, currentPage);                List<News> list = newsDao.queryByPage(hql, offset, pageSize);                     pageBean.setList(list);        pageBean.setAllRows(allRows);        pageBean.setCurrentPage(currentPage);        pageBean.setTotalPage(totalPage);        return pageBean;    }    }

7.Action层设计,定义一个NewsAction:

public class NewsAction extends ActionSupport {    //注解注入属性实例    @Resource(name="myNewsService")    private NewsService newsService;    private int page;    public int getPage() {        return page;    }    public void setPage(int page) {        this.page = page;    }         @Override    public String execute(){                 //表示每页显示5条记录,page表示当前网页        PageBean pageBean = newsService.getPageBean(5, page);        HttpServletRequest request = ServletActionContext.getRequest();                request.setAttribute("pageBean", pageBean);                return SUCCESS;    }}

9.配置struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <!-- 告知Struts2运行时使用Spring来创建对象 -->    <constant name="struts.objectFactory" value="spring" />    <package name="mypck001" extends="struts-default" namespace="/">            <action name="NewsAction" class="myNewsAction" method="execute">            <result name="success">/WEB-INF/jsp/index.jsp</result>        </action>            </package></struts>

10.配置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:p="http://www.springframework.org/schema/p"          xmlns:aop="http://www.springframework.org/schema/aop"           xmlns:context="http://www.springframework.org/schema/context"          xmlns:jee="http://www.springframework.org/schema/jee"          xmlns:tx="http://www.springframework.org/schema/tx"          xsi:schemaLocation="                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">    <!-- 原理:自动注入processor解析器,用来解析注解 -->    <context:annotation-config />         <context:property-placeholder location="classpath:jdbc.properties" />        <bean id="myNewsAction" class="sshPage.action.NewsAction" scope="prototype">        </bean>                                        <bean id="myNewsService" class="sshPage.service.NewsServiceImpl" scope="prototype">        </bean>        <bean id="myNewsDao" class="sshPage.dao.NewsDAOImpl" scope="prototype">    </bean>        <bean id="myPageBean" class="sshPage.pageBean.PageBean" scope="prototype">    </bean>  <bean id="mySessionFactory_mysql" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >        <property name="dataSource" ref="mysql_DataSource"></property>        <property name="hibernateProperties">            <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>                <prop key="hibernate.show_sql">true</prop>                <prop key="hibernate.format_sql">true</prop>                <prop key="hibernate.connection.autocommit">false</prop>                <prop key="hibernate.hbm2ddl.auto">update</prop>            </props>        </property>                <property name="mappingResources">            <list>                <value>sshPage/entity/News.hbm.xml</value>            </list>        </property>        </bean>        <!-- 数据库连接池 mysql_DataSource-->    <!-- c3p0 -->    <bean id="mysql_DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">         <property name="driverClass" value="${mysql.driver}" />         <property name="jdbcUrl" value="${mysql.url}" />        <property name="user" value="${mysql.userName}" />        <property name="password" value="${mysql.password}" />                <property name="idleConnectionTestPeriod" value="300"></property>        <property name="maxIdleTime" value="900"></property>        <property name="maxPoolSize" value="2"></property>    </bean></beans>

11.最后也就是JSP页面index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="/struts-tags" prefix="s" %><%@ page import="java.util.*"%><!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>Insert title here</title><script type="text/javascript">        function validate()    {        var page = document.getElementsByName("page")[0].value;                    if(page > <s:property value="#request.pageBean.totalPage"/>)        {            alert("你输入的页数大于最大页数,页面将跳转到首页!");                        window.document.location.href = "NewsAction";                        return false;        }                return true;    }</script></head><body>    <h1><font color="blue">分页查询</font></h1><hr>        <table border="1" align="center" bordercolor="yellow" width="50%">            <tr>            <th>Id</th>            <th>Title</th>            <th>Content</th>            <th>Begintime</th>            <th>Username</th>        </tr>            <s:iterator value="#request.pageBean.list" id="news">            <tr>            <td><s:property value="#news.id"/></td>            <td><s:property value="#news.title"/></td>            <td><s:property value="#news.content"/></td>            <td><s:date name="#news.begintime" format="yyyy年MM月dd日"></s:date></td>            <td><s:property value="#news.username"></s:property></td>                </tr>        </s:iterator>        </table>    <b></b>    <center>            <font size="5"><font color="red"><s:property value="#request.pageBean.totalPage"/></font></font>&nbsp;&nbsp;        <font size="5"><font color="red"><s:property value="#request.pageBean.allRows"/></font>条记录</font><br><br>        <font size="5"><font color="red"><s:property value="#request.pageBean.currentPage"/></font></font>        <s:if test="#request.pageBean.currentPage == 1">            首页&nbsp;&nbsp;&nbsp;上一页        </s:if>                <s:else>            <a href="NewsAction.action">首页</a>            &nbsp;&nbsp;&nbsp;            <a href="NewsAction.action?page=<s:property value="http://www.mamicode.com/#request.pageBean.currentPage - 1"/>">上一页</a>        </s:else>                <s:if test="#request.pageBean.currentPage != #request.pageBean.totalPage">            <a href="NewsAction.action?page=<s:property value="http://www.mamicode.com/#request.pageBean.currentPage + 1"/>">下一页</a>            &nbsp;&nbsp;&nbsp;            <a href="NewsAction.action?page=<s:property value="http://www.mamicode.com/#request.pageBean.totalPage"/>">尾页</a>        </s:if>                <s:else>            下一页&nbsp;&nbsp;&nbsp;尾页        </s:else>        </center><br>        <center>                <form action="NewsAction" onsubmit="return validate();">            <font size="4">跳转至</font>            <input type="text" size="2" value=‘<s:property value="#request.pageBean.currentPage"/>‘ name="page">页            <input type="submit" value="跳转">        </form>            </center></body></html>

页面效果图如下:

技术分享

 

实现分页就差不多到这了,如果有不懂的地方,可以评论区给我留言,谢谢!

 

struts2+spring+hibernate 实现分页