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&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
-----------------------------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值