`
qxmcool
  • 浏览: 90853 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

struts1.x+hibernate+dao分页

阅读更多
<%@ page language="java" pageEncoding="utf-8"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />

<title>mangpage.jsp</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<table>
<tr>
<td>
学生id
</td>
<td>
学生姓名
</td>
<td>
学生密码
</td>
</tr>
<logic:iterate id="stu" name="pc" property="smallList">
<tr>
<td>
<bean:write name="stu" property="id" />
</td>
<td>
<bean:write name="stu" property="username" />
</td>
<td>
<bean:write name="stu" property="password" />
</td>
</tr>
</logic:iterate>
</table>
<html:link action="/manyPage.do?pageindex=1">首页</html:link>
<logic:equal name="pc" property="firstPage" value="false">
<html:link action="/manyPage.do" paramId="pageindex" paramName="pc"
paramProperty="previousPageCount">上一页</html:link>
</logic:equal>
<logic:equal name="pc" property="lastPage" value="false">
<html:link action="/manyPage.do" paramId="pageindex" paramName="pc"
paramProperty="nextPageCount">下一页</html:link>
</logic:equal>
<html:link action="/manyPage.do1" paramId="pageindex" paramName="pc" paramProperty="allPage">尾页</html:link>
</body>
</html:html>

-----------------------------------------------------------

对应实体类

package com.qxm.pojo;

import java.io.Serializable;

public class Student implements Serializable {

private static final long serialVersionUID = 1L;

private int id;

private String username;

private String password;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

------------------------------------------------------------

对应实体类的配置文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class table="T_suudent" name="com.qxm.pojo.Student">
    <id access="field" name="id">
      <generator class="native"/>
    </id>
    <property name="username" access="field"/>
     <property name="password" access="field"/>
  </class>
</hibernate-mapping>

-----------------------------------------------------------
hibernate的配置文件

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/manypage?useUnicode=true&amp;characterEncoding=utf-8
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="show_sql">true</property>
<mapping resource="com/qxm/pojo/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>
-----------------------------------------------------------

dao层

package com.qxm.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.qxm.pojo.Student;
import com.qxm.utils.HibernateSessionFactory;

@SuppressWarnings("unchecked")
public class ManyPageDao {

public ArrayList<Student> StudentLookUp(){

ArrayList<Student> alist = null;
Session session = HibernateSessionFactory.getSession();
try {
List list = session.createQuery("from com.qxm.pojo.Student").list();
alist = new ArrayList<Student>();
for(Iterator it = list.iterator();it.hasNext();){
Student stu = new Student();
stu = (Student)it.next();
alist.add(stu);
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
session.close();
}
return alist;
}
}

-----------------------------------------------------------
action
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.qxm.struts.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.qxm.dao.ManyPageDao;
import com.qxm.manypage.PageController;
import com.qxm.pojo.Student;

public class ManyPageAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {

String currentPage = request.getParameter("pageindex");
if(currentPage == null){
currentPage = "1";
}
int cp = Integer.parseInt(currentPage);
PageController pc = (PageController)request.getAttribute("pc");

if(pc == null){
pc = new PageController();
ManyPageDao dao = new ManyPageDao();
ArrayList<Student> bigList = dao.StudentLookUp();
pc.setBigList(bigList);
request.setAttribute("pc", pc);
}
pc.setCurrentPage(cp);

return mapping.findForward("display_success");
}
}
-----------------------------------------------------------
分页逻辑

package com.qxm.manypage;

import java.util.ArrayList;

import com.qxm.pojo.Student;

@SuppressWarnings("unchecked")
public class PageController {

private ArrayList bigList; // 存储所有数据的集合
private int currentPage = 1; // 当前页数
private int allPage; // 总页数
private int countNumber = 5; // 每页数据的条数
private int allCountNumber; // 数据的总条数
private ArrayList smallList;// 每页数据的小集合
private int previousPageCount;// 上一页的页数
private int nextPageCount;// 下一页的页数
private boolean firstPage;// 是否是第一页
private boolean lastPage;// 是否是最后一页

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
smallList = new ArrayList<Student>();
//上一页
previousPageCount = currentPage-1;
//下一页
nextPageCount = currentPage+1;

if(currentPage == 1){
firstPage = true;
}
else{
firstPage = false;
}
if(currentPage == allPage){
lastPage = true;
}
else{
lastPage = false;
}

for(int i = (currentPage-1)*countNumber;i<currentPage*countNumber&&i<allCountNumber;i++){
smallList.add(bigList.get(i));
}
}
public void setBigList(ArrayList bigList) {
this.bigList = bigList;
allCountNumber = bigList.size();
if(allCountNumber%countNumber==0){
allPage = allCountNumber/countNumber;
}
else{
allPage = allCountNumber/countNumber+1;
}
}

public int getCurrentPage() {
return currentPage;
}

public ArrayList getBigList() {
return bigList;
}


public int getAllPage() {
return allPage;
}

public void setAllPage(int allPage) {
this.allPage = allPage;
}

public int getCountNumber() {
return countNumber;
}

public void setCountNumber(int countNumber) {
this.countNumber = countNumber;
}

public int getAllCountNumber() {
return allCountNumber;
}

public void setAllCountNumber(int allCountNumber) {
this.allCountNumber = allCountNumber;
}

public ArrayList getSmallList() {
return smallList;
}

public void setSmallList(ArrayList smallList) {
this.smallList = smallList;
}

public int getPreviousPageCount() {
return previousPageCount;
}

public void setPreviousPageCount(int previousPageCount) {
this.previousPageCount = previousPageCount;
}

public int getNextPageCount() {
return nextPageCount;
}

public void setNextPageCount(int nextPageCount) {
this.nextPageCount = nextPageCount;
}

public boolean isFirstPage() {
return firstPage;
}

public void setFirstPage(boolean firstPage) {
this.firstPage = firstPage;
}

public boolean isLastPage() {
return lastPage;
}

public void setLastPage(boolean lastPage) {
this.lastPage = lastPage;
}
}

-----------------------------------------------------------

建表类

package com.qxm.utils;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class ExportDB {

/**
* @param args
*/
public static void main(String[] args) {

Configuration cfg = new Configuration().configure();

SchemaExport se = new SchemaExport(cfg);

se.create(true, true);

}

}

-----------------------------------------------------------

hibernatesessionfactory
package com.qxm.utils;

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

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

static {
    try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
    }
    private HibernateSessionFactory() {
    }

/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    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;
    }

/**
     *  Rebuild hibernate session factory
     *
     */
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

/**
     *  return session factory
     *
     */
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
     *  return session factory
     *
     * session factory will be rebuilded in the next call
     */
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
     *  return hibernate configuration
     *
     */
public static Configuration getConfiguration() {
return configuration;
}

}
-----------------------------------------------------------
log4j
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=d:/oa.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
log4j.logger.com.bjsxt = debug
-----------------------------------------------------------
分享到:
评论

相关推荐

    45-使用Struts + DAO + Hibernate完成分页.rar

    45-使用Struts + DAO + Hibernate完成分页.rar

    经典struts+hibernate结合的电影售票系统项目

    电影售票系统采用struts+hibernate再结合java的dao模式框架做的,具有典型的mvc结构,在后台操作电影影片中:在添加电影这步,我用了上传案例结合hibernate的添加数据功能成功的将电影封面上传到了指定位置,一部...

    JAVA WEB典型模块与项目实战大全

    3.4 实现spring、struts2.x和hibernate框架集成  3.5 小结  第2篇 典型模块开发  第4章 在线文本编辑器(fckeditor)  4.1 分析fckeditor在线文本编辑器  4.2 fckeditor在线文本编辑器初级应用  4.3 ...

    struts+hibernate分页

    struts+hibernate分页。采用maysql数据库。采用DAO模式。里面有备份好的数据库

    javaEE框架笔记,识货人下

    12-Struts + DAO分页笔记.pdf 13-Hibernate入门(上)笔记.pdf 14-Hibernate入门(下)笔记.pdf 15-Hibernate数据检索(HQL)笔记.pdf 16-留言管理程序_使用Struts + DAO + Hibernate完成笔记.pdf 17-Hibernate实体...

    Struts2 Spring3 Hibernate 注解功能 DAO 泛型 通用分页

    Struts2 Spring3 Hibernate 注解功能 DAO 泛型 通用分页

    Struts+Hibernate+Sprign 通用分页

    作品吹牛: ...通用Hibernate Dao 最后真心话! 力行 一个星期完成! 第一次 心血之作 所以望大家体谅给点支持! 好请给予支持,坏请给予批评并且指正! 在次感谢大家的支持。。。 留言QQ:308117229

    (2.0版本)自己写的struts2+hibernate+spring实例

    aop.jar spring-dao.jar spring-hibernate.jar spring-jdbc.jar spring-mock.jar spring-orm.jar spring-remoting.jar spring-support.jar spring-webmvc.jar

    J2EE三大框架_笔记_a

    12-Struts + DAO分页笔记 16-留言管理程序_使用Struts + DAO + Hibernate完成笔记 17-Hibernate实体映射笔记 18-Hibernate复合主键笔记 20-22Hibernate_容器映射技术笔记 23-26Hibernate数据关联技术笔记 27-32...

    J2EE框架_笔记_c

    12-Struts + DAO分页笔记 16-留言管理程序_使用Struts + DAO + Hibernate完成笔记 17-Hibernate实体映射笔记 18-Hibernate复合主键笔记 20-22Hibernate_容器映射技术笔记 23-26Hibernate数据关联技术笔记 27-32...

    SSH整合(struts2+hibernate+spring)

    用SSH做的简易论坛系统,功能算丰富,CRUD,...开始先要对板块插入数据,表可以用hibernate的自动创建,hibernate和spring用的都是注解技术,dao层用了江南白衣的思想,已封装,测试过,我没发现bug,希望对你有所帮助

    J2EE框架_笔记_b

    12-Struts + DAO分页笔记 16-留言管理程序_使用Struts + DAO + Hibernate完成笔记 17-Hibernate实体映射笔记 18-Hibernate复合主键笔记 20-22Hibernate_容器映射技术笔记 23-26Hibernate数据关联技术笔记 27-32...

    李兴华\struts\45-使用Struts _ DAO _ Hibernate完成分页

    李兴华\struts\45-使用Struts _ DAO _ Hibernate完成分页

    java大作业基于SSH框架的学生成绩管理系统源码.zip

    (1) 整合Struts2、Spring和Hibernate框架 (2) 实现“登录”功能 (3) 实现“学生信息管理”功能 (4) 实现“学生成绩管理”功能 (5) 实现分页功能 目的: 掌握Struts2的开发步骤 掌握Hibernate的开发...

    struts2+spring+hibernate分页代码[比较多]第1/7页

    dao层接口: Java代码 代码如下: package com.last999.im.news.dao; import java.util.*; import com.last999.im.news.entity.KindEntity; import com.last999.im.news.web.PageTool; public interface ...

    SSH学习基础笔记 .zip

    1-JSP+JDBC_假分页笔记.pdf 2-JSP+JDBC_真分页(基于Oracle数据库分页)笔记.pdf 3-JSP+DAO和MVC+DAO(基于MySQL数据库分页)-v笔记.pdf 4-Struts入门笔记.pdf ...54留言管理程序_Struts + Spring + Hibernate笔记.pdf

    SSH 泛型DAO分页

    Struts2.1.6+Spring2.5.6+Hibernate3.3.2+mysql整合+分页模板 能用

    Struts_DAO 实现分页

    本程序采用struts 和dao 实现分页功能: 支持多条件模糊查询 简单配置一下,就可重用 下单元将给出struts hibernate 分页代码

Global site tag (gtag.js) - Google Analytics