iLeichun

当前位置: 首页 > J2EE

Struts2+Hibernate实现分页

分类:J2EE   来源:网络   时间:2011-11-07 21:34:59

实际开发中,Struts2+Hibernate实现分页是JAVA WEB最常用的东西了,本文将分步为您分享如何进行分页操作,有不足之处请指出,希望与大家一起进步。

第一步:建立一个SQL数据库Tb_soft ,数据库表,software(字段:Tsoftware,fSoftname,fListImage,fVar,fFeilname,fUsedSystem,fUpdateTime,fInf,fClassID,fDownTimes  字段

类型并不重要自己随便设置然后直接通过SQL企业管理器直接在表里输入内容方便测试就是了)

第二步:建立一个名为productlist JAVA的WEB项目(我用的是NetBeans IDE 6.9,所以在新建项目的时候选择了Struts2 HIBERNATE框架,新建后会自动生成 hibernate.cfg.xml的配置文件

)。

第三步:配置hibernate.cfg.xml文件,主要是对数据库的链接设置以及数据表映射文件的设置

1、文件名:hibernate.cfg.xml文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Tb_soft </property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password">123456</property>
    <mapping resource="soft.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

注: <mapping resource="soft.hbm.xml"/> 元素对数据库表software 配置文件soft.hbm.xml的映射配置,注意soft.hbm.xml文件的路径如果和hibernate.cfg.xml文件没在同一个目录必须

加上路径例如 <mapping resource="DatatableXML/soft.hbm.xml"/>

2、新建 名为:soft.hbm.xml 的映射文件,该文件主要是对数据库表software的映射配置全部代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name= "com.bean.soft" table="Tsoftware">
        <id name="id" column="id" type="int">
            <generator class="native"/>
        </id>
        <property name="fSoftname" type="string" length="20">
            <column name="fSoftname"/>
        </property>
        <property name="fListImage" type="string"  length="20">
            <column name="fListImage"/>
        </property>
        <property name="fVar" type="string" length="10">
            <column name="fVar"/>
        </property>
        <property name="fFeilname" type="string"  length="30">
            <column name="fFeilname"/>
        </property>
        <property name="fUsedSystem" type="string"  length="30">
            <column name="fUsedSystem"/>
        </property>
        <property name="fUpdateTime" type="string"  length="30">
            <column name="fUpdateTime"/>
        </property>
        <property name="fInf" type="string"  length="2000">
            <column name="fInf"/>
        </property>
        <property name="fDownTimes" type="string" length="10">
            <column name="fDownTimes"/>
        </property>
    </class>
</hibernate-mapping>


注: <class name= "com.bean.soft" table="Tsoftware">设置了soft属于一个javabean,关于javabean我就不解释了。关于这个文件的代码后面再贴出来。class name=javabean包

+javabean构成, table="Tsoftware",其中Tsoftware就是SQL数据库表。有关property 元素我这里简单的说一下 例如下:

       <property name="fDownTimes" type="string" length="10">
            <column name="fDownTimes"/>
        </property>
 name,映射文件构成表的的字段名,这里的name必须与com.bean.soft 中的熟悉对应,千万记住要设置好type ,这里的type好比SQL的字段类型,具体类型对应关系请查相关资料我就不详细解

释了。

第四步:在包com.bean 建立JAVAbean soft 代码如下:

package com.bean;

/**
 *
 * @author Even
 */
public class soft {
    private String fSoftname;
    private int id;
    private String fListImage;
    private String fVar;
    private String fFeilname;
    private String fUsedSystem;
    private String fUpdateTime;
    private String fInf;
    private String fDownTimes;

    /**
     * @return the fSoftname
     */
    public String getfSoftname() {
        return fSoftname;
    }

    /**
     * @param fSoftname the fSoftname to set
     */
    public void setfSoftname(String fSoftname) {
        this.fSoftname = fSoftname;
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the fListImage
     */
    public String getfListImage() {
        return fListImage;
    }

    /**
     * @param fListImage the fListImage to set
     */
    public void setfListImage(String fListImage) {
        this.fListImage = fListImage;
    }

    /**
     * @return the fVar
     */
    public String getfVar() {
        return fVar;
    }

    /**
     * @param fVar the fVar to set
     */
    public void setfVar(String fVar) {
        this.fVar = fVar;
    }

    /**
     * @return the fFeilname
     */
    public String getfFeilname() {
        return fFeilname;
    }

    /**
     * @param fFeilname the fFeilname to set
     */
    public void setfFeilname(String fFeilname) {
        this.fFeilname = fFeilname;
    }

    /**
     * @return the fUsedSystem
     */
    public String getfUsedSystem() {
        return fUsedSystem;
    }

    /**
     * @param fUsedSystem the fUsedSystem to set
     */
    public void setfUsedSystem(String fUsedSystem) {
        this.fUsedSystem = fUsedSystem;
    }

    /**
     * @return the fUpdateTime
     */
    public String getfUpdateTime() {
        return fUpdateTime;
    }

    /**
     * @param fUpdateTime the fUpdateTime to set
     */
    public void setfUpdateTime(String fUpdateTime) {
        this.fUpdateTime = fUpdateTime;
    }

    /**
     * @return the fInf
     */
    public String getfInf() {
        return fInf;
    }

    /**
     * @param fInf the fInf to set
     */
    public void setfInf(String fInf) {
        this.fInf = fInf;
    }

    /**
     * @return the fDownTimes
     */
    public String getfDownTimes() {
        return fDownTimes;
    }

    /**
     * @param fDownTimes the fDownTimes to set
     */
    public void setfDownTimes(String fDownTimes) {
        this.fDownTimes = fDownTimes;
    }
}
关于JAVAbean就不解释了。

第五步:在com.Hibernate包建立Hibernate的sessionFactory(文件名:NewHibernateUtil.java)用于获取Session

NewHibernateUtil.java 代码:

package com.Hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Even
 */
public class NewHibernateUtil {

    private static SessionFactory sessionFactory = null;
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("对不起数据工厂构建失败." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getsession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildsessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            threadLocal.set(session);
        }
        return session;
    }

    private static void rebuildsessionFactory() {
        try {
            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();
        } catch (Exception e) {
            System.out.print("创建工厂会话失败!");
            e.printStackTrace();
        }
    }

    public static SessionFactory getsessionFactory() {
        return sessionFactory;
    }

    public static void closesessicon() {
        Session session = (Session) threadLocal.get();
        if (session != null) {
            session.close();
        }
    }
}

这里注意session的关闭。

第六步:在包com.dao包建立整个程序的dao层;文件名为:softDao.java

代码如下:


package com.dao;

/**
 *
 * @author Even
 */
import com.Hibernate.NewHibernateUtil;
import com.bean.soft;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class softDao {
    public List<soft> queryByPage(int pageSize, int pageNow, String HQL) {
        Session session = null;
        List sftlist = new ArrayList();
        try {
            session = NewHibernateUtil.getsession();// 获得session对象
            //String hql = "from Employee emp";// 查询HQL语句
            HQL = "from soft sft";// 条件查询HQL语句
            Query q = session.createQuery(HQL);// 执行查询操作
            q.setFirstResult(pageSize * (pageNow - 1));
            q.setMaxResults(pageSize);
            sftlist = q.list();
        } catch (HibernateException e) {
            e.printStackTrace();
            System.out.println("查询失败");
        } finally {
            NewHibernateUtil.closesessicon();// 关闭session
        }
        return sftlist;
    }
    //获得总页数的方法有时间可能会单独使用该工程所以将获得session的过程也单独写出来
    public int getpageCount(int pagesize, String HQL) {
        int pageCount;
        int Datacount = 0;
        Session session = null;
        try {
            session = NewHibernateUtil.getsession();// 获得session对象
            HQL = "from soft sft";//条件查询HQL语句,这里注意使用的实例查询方式,soft是我们建立的javabean
            Query q = session.createQuery(HQL);// 执行查询操作
            Datacount = q.list().size();//获得记录总数
        } catch (HibernateException e) {
            e.printStackTrace();
            System.out.println("查询失败");
        } finally {
            NewHibernateUtil.closesessicon();// 关闭session
        }
        if (Datacount % pagesize == 0) {
            pageCount = Datacount / pagesize;
        } else {
            pageCount = Datacount / pagesize + 1;
        }
    
        return pageCount;

    }
}

这里就不多解释了。

第七步:在包com.action 建立分页的Action文件名为:softlistAction.java

代码如下:

package com.action;

import com.bean.leavetalk;
import com.bean.soft;
import com.dao.Dao;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class softlistAction extends ActionSupport {

    private List<soft> softs;//用于数据集合对象并非只是软件
    private List<soft> downcountlist;//显示下载列表的集合
    private List<leavetalk> leavatalks;//显示用户留言列表的集合
    private int pageNow = 1; //默认从第一页开始显示
    private int pageSize = 4; //每页显示5条
    private int pageCount;//总页数
    private String doing;//标记Action返回的值
    private Dao pageDAO = new Dao();
    private Dao leivetalkdao = new Dao();
    private int id;
    private String fbadcount;
    private String fgoodcount;

    public List<soft> getSofts() {
        return softs;
    }

    public void setSofts(List<soft> softwares) {
        this.softs = softs;
    }

    public int getPageNow() {
        return pageNow;
    }

    public void setPageNow(int pageNow) {
        this.pageNow = pageNow;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getPageCount() {
        Dao sa = new Dao();
        sa.getpageCount(pageSize, "");
        this.pageCount = sa.getpageCount(pageSize, "");
        return sa.getpageCount(pageSize, "");
    }

    /**
     * @param pageCount the pageCount to set
     */
    public void setPageCount() {
        Dao sa = new Dao();
        sa.getpageCount(pageSize, "");
        this.pageCount = sa.getpageCount(pageSize, "");
    }

    /**
     * @return the doing
     */
    public String getDoing() {
        return doing;
    }

    /**
     * @param doing the doing to set
     */
    public void setDoing(String doing) {
        this.doing = doing;
    }

    //主方法
    public String execute() throws Exception {
        String returnstr = "erro";
        String HQLstr = "";
        // softs = pageDAO.queryByPage(pageSize, pageNow, HQLstr);
        if (doing.equals("productlist")) {
            returnstr = "productlist";
            HQLstr = "from soft sft";
            this.setPageSize(4);
            this.leavatalks = leivetalkdao.getleavetalks("from leavetalk lt order by lt.id desc");
            this.softs = pageDAO.queryByPage(pageSize, pageNow, HQLstr);

        } else if (doing.equals("productshow")) {
            returnstr = "productshow";
            HQLstr = "from soft sft where sft.id=¹" + getId() + "¹ order by sft.id asc";
            downcountlist = pageDAO.queryByPage(10, pageNow, "from soft sft order by sft.fDownTimes desc");

        } else if (doing.equals("index")) {
            returnstr = "index";
            HQLstr = " from soft sft where sft.ftype=¹T¹order by sft.id asc";
            this.setPageSize(5);
        } else if (doing.equals("web")) {
            returnstr = "web";
            HQLstr = " from soft sft where sft.ftype=¹T¹order by sft.id asc";
            this.setPageSize(5);
        } else if (doing.equals("service")) {
            returnstr = "service";
            //HQLstr = " from service sr where order by sr.id asc";
            // this.setPageSize(1);
        } else if (doing.equals("Updatefgood")) {
            returnstr = "Updatefgood";
            HQLstr = "from soft sft where sft.id=¹" + getId() + "¹ order by sft.id asc";
            downcountlist = pageDAO.queryByPage(10, pageNow, "from soft sft order by sft.fDownTimes desc");
            pageDAO.UpdatefgoodAndfbad(getId(), "updategood", fgoodcount);
        } else if (doing.equals("Updatefbad")) {
            returnstr = "Updatefgood";
            HQLstr = "from soft sft where sft.id=¹" + getId() + "¹ order by sft.id asc";
            downcountlist = pageDAO.queryByPage(10, pageNow, "from soft sft order by sft.fDownTimes desc");
            pageDAO.UpdatefgoodAndfbad(getId(), "updatebad", fbadcount);
        } else {
            returnstr = "erro";
        }
        softs = pageDAO.queryByPage(pageSize, pageNow, HQLstr);
      
        System.out.println(softs.size());
         return returnstr;
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the downcountlist
     */
    public List<soft> getDowncountlist() {
        return downcountlist;
    }

    /**
     * @param downcountlist the downcountlist to set
     */
    public void setDowncountlist(List<soft> downcountlist) {
        this.downcountlist = downcountlist;
    }

    /**
     * @return the fbadcount
     */
    public String getFbadcount() {
        return fbadcount;
    }

    /**
     * @param fbadcount the fbadcount to set
     */
    public void setFbadcount(String fbadcount) {
        Integer b = Integer.valueOf(fbadcount) + 1;
        this.fbadcount = b.toString();

    }

    /**
     * @return the fgoodcount
     */
    public String getFgoodcount() {
        return fgoodcount;
    }

    /**
     * @param fgoodcount the fgoodcount to set
     */
    public void setFgoodcount(String fgoodcount) {
        Integer b = Integer.valueOf(fgoodcount) + 1;
        this.fgoodcount = b.toString();
    }

    /**
     * @return the leavatalks
     */
    public List<leavetalk> getLeavatalks() {
        return leavatalks;
    }

    /**
     * @param leavatalks the leavatalks to set
     */
    public void setLeavatalks(List<leavetalk> leavatalks) {
        this.leavatalks = leavatalks;
    }
}
 


第八步:配置ACTION 文件STRUTS.xml的代码如下:

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="softlist" class="com.action.softlistAction">
            <result name="SUCCESS">test.jsp</result>
            <result name="error">error.jsp</result>
        </action>
    </package>
</struts>

第九步:建立JSP文件 来享受结果了

test.jsp代码如下:
< import="java.sql.ResultSet"%>
< import="java.util.List"%>
< contentType="text/html"%>
< import="org.apache.struts2.ServletActionContext"%>
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<script language="javascript" type="text/javascript">
        <%
                    String PageNow = request.getAttribute("pageNow").toString();
                    String pageCount = request.getAttribute("pageCount").toString();
        %>
          
    </script>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        <title>分页测试</title>
    </head>

    <table style=" border: 2px">
        <s:iterator value="softs">
            <td><s:property value="fSoftname"/></td>
            <td><s:property value="fUsedSystem"/></td>
            <td><s:property value="fUpdateTime"/></td>
        </s:iterator>
    </table>
    <div>
                        <ul><li><a href=¹softlist.action?pageNow=1¹>首页</a></li>
                            <li><a href=¹softlist.action?pageNow=<s:property value="%{PageNow-1}"/>¹> 上一页</a></li>
                            <li><a href=¹softlist.action?pageNow=<s:property value="%{PageNow+1}"/>¹>下一页</a></li>
                            <li><a href=¹softlist.action?pageNow=<%=pageCount%>¹>末页</a></li>
                            <li><span class="pageinfo">第<strong><s:property value="#request.pageNow"/></strong>页</span></li>
                            <li><span class="pageinfo">共<strong><s:property value="#request.pageCount"/></strong>页</span></li>
                        </ul></div>
    <body>
     
    </body>
</html>
第十步:建立link.jsp
代码:
<%--
    Document   : link
    Created on : 2011-1-24, 18:42:14
    Author     : Even
--%>

< contentType="text/html" pageEncoding="GBK"%>
<!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=GBK">
        <title>JSP Page</title>
    </head>
    <body>
        <h1><a href="softlist.action">单击显示效果</a></h1>
    </body>
</html>

注意:后面的演示我是重新制作的页面不是我的网站页面效果所以只是完成了一个原理而已,网上很多 STRUTS2的分页文章没有一个完整的。这里面的分页原理用的是 session里面的记录集查询中的 setFirstResult和setMaxResults,关于算法大家自己去揣摩就是了很简单。

来自: http://hi.baidu.com/sunnywfg/blog/item/4aa5a563acbe5e730d33fa3f.html

更多