一个完整的struts2+spring+hibernate+分页实例

一个完整的struts2+spring+hibernate+分页实例

前段时间,一直在为配置struts2+spring+hibernate这三大框架头痛。在网上找了很多例子,但都没有解决好我的三大框架的问题。后来把它搁了一段时间。偶尔有一天,我突然想起来了,然后硬着头皮逐字逐字地反复看那几个配置文件,突然我发现,原来犯了个很cheap的错误。敲错了一个字母。导致tomcat启动时老报Error:listenStart...的错误。这个错误可真烦人啊。
以下这个实例在我的机器上运行是没问题的。在此共享一下:

一。 看树:(定位各文件的正确放置)
卷 drfStudy 的文件夹 PATH 列表
卷序列号为 F4AB-013D
E:\ECLIPSEWORKS\PAGING
│  .classpath
│  .myhibernatedata
│  .mymetadata
│  .project
│  .springBeans
│  treeList.txt
│ 
├─.myeclipse
├─src
│  │  applicationContext-beans.xml
│  │  applicationContext-common.xml
│  │  create.sql
│  │  create.sql.bak
│  │  hibernate.cfg.xml
│  │  instance.txt
│  │  instance.txt.bak
│  │  log4j.properties
│  │  select.sql
│  │  struts.xml
│  │ 
│  └─cn
│      └─paging
│          ├─action
│          │      ListMemberAction.java
│          │     
│          ├─bean
│          │      PageBean.java
│          │     
│          ├─dao
│          │  │  MemberDao.java
│          │  │ 
│          │  └─impl
│          │          MemberDaoImpl.java
│          │         
│          ├─model
│          │      Member.hbm.xml
│          │      Member.java
│          │     
│          ├─service
│          │  │  MemberService.java
│          │  │ 
│          │  └─impl
│          │          MemberServiceImpl.java
│          │         
│          ├─test
│          └─util
│                  HibernateUtils.java
│                 
└─WebRoot
    │  index.jsp
    │  list.jsp
    │  update.jsp
    │ 
    ├─META-INF
    │      MANIFEST.MF
    │     
    └─WEB-INF
        │  spring-form.tld
        │  spring.tld
        │  web.xml
        │ 
        ├─classes
        │  │  applicationContext-beans.xml
        │  │  applicationContext-common.xml
        │  │  create.sql
        │  │  create.sql.bak
        │  │  hibernate.cfg.xml
        │  │  instance.txt
        │  │  instance.txt.bak
        │  │  log4j.properties
        │  │  select.sql
        │  │  struts.xml
        │  │ 
        │  └─cn
        │      └─paging
        │          ├─action
        │          │      ListMemberAction.class
        │          │     
        │          ├─bean
        │          │      PageBean.class
        │          │     
        │          ├─dao
        │          │  │  MemberDao.class
        │          │  │ 
        │          │  └─impl
        │          │          MemberDaoImpl.class
        │          │         
        │          ├─model
        │          │      Member.class
        │          │      Member.hbm.xml
        │          │     
        │          ├─service
        │          │  │  MemberService.class
        │          │  │ 
        │          │  └─impl
        │          │          MemberServiceImpl.class
        │          │         
        │          ├─test
        │          └─util
        │                  HibernateUtils.class
        │                 
        └─lib
                antlr-2.7.5H3.jar
                asm-attrs.jar
                asm-commons-2.2.3.jar
                asm.jar
                aspectjweaver.jar
                c3p0-0.9.1.1.jar
                cglib-2.1.3.jar
                cglib-nodep-2.1_3.jar
                commons-attributes-api.jar
                commons-attributes-compiler.jar
                commons-codec.jar
                commons-collections-2.1.1.jar
                commons-dbcp.jar
                commons-fileupload.jar
                commons-io.jar
                commons-lang.jar
                commons-logging.jar
                commons-pool-1.3.jar
                concurrent-1.3.2.jar
                connector.jar
                cos.jar
                dom4j-1.6.1.jar
                ehcache-1.1.jar
                ehcache-1.2.4.jar
                freemarker.jar
                hibernate-annotations.jar
                hibernate-commons-annotations.jar
                hibernate-entitymanager.jar
                hibernate3.jar
                ibatis-2.3.0.677.jar
                jotm.jar
                jta.jar
                jxl.jar
                log4j-1.2.14.jar
                mysql-connector-java-5.1.6-bin.jar
                ognl-2.6.11.jar
                oscache-2.1.jar
                spring-agent.jar
                spring-aop.jar
                spring-beans.jar
                spring-context.jar
                spring-core.jar
                spring-dao.jar
                spring-hibernate3.jar
                spring-ibatis.jar
                spring-jca.jar
                spring-jdbc.jar
                spring-jdo.jar
                spring-jms.jar
                spring-jpa.jar
                spring-portlet.jar
                spring-struts.jar
                spring-tomcat-weaver.jar
                spring-toplink.jar
                spring-web.jar
                spring-webmvc.jar
                spring.jar
                struts2-core-2.0.11.jar
                struts2-spring-plugin-2.0.11.2.jar
                xapool.jar
                xerces-2.6.2.jar
                xwork-2.0.4.jar
               

二。看配置文件(spring,struts,hibernate,web)
(一)spring的配置文件。(在此我用了两个,请对照上面的树放入相应的位置)
1.applicationContext-beans.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-2.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">      
    <!-- action  -->
<bean id="listAction" class="cn.paging.action.ListMemberAction" scope="prototype">
  <property name="memberService">
   <ref local="memberService" />
  </property>
  <property name="pageBean">
   <ref bean="pageBean"/>
  </property>
</bean>
    

<bean id="memberService" class="cn.paging.service.impl.MemberServiceImpl" scope="prototype">
  <property name="memberDao">
   <ref bean="memberDao"/>
  </property>
</bean>


<bean id="memberDao" class="cn.paging.dao.impl.MemberDaoImpl" scope="prototype">
  <property name="sessionFactory">
   <ref bean="sessionFactory"/>
  </property>
</bean>

<bean id="pageBean" class="cn.paging.bean.PageBean" scope="prototype" >
</bean>
</beans>
//**************************************************************************************************

2.applicationContext-common.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-2.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">      
          
          
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation">
   <value>classpath:hibernate.cfg.xml</value>
  </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory"/>
  </property>
</bean>

<!-- intercept methods -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="add*" propagation="REQUIRED" />
   <tx:method name="del*" propagation="REQUIRED"/>
   <tx:method name="list*" propagation="REQUIRED"/>
   <tx:method name="update*" propagation="REQUIRED"/>
   <tx:method name="edit*" propagation="REQUIRED"/>
   <tx:method name="*" read-only="true" />
  </tx:attributes>
</tx:advice>
 
<aop:config>
  <aop:pointcut id="allManagerMethod" expression="execution(* cn.paging.service.*.*(..))"/>
  <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>


</beans>
//**************************************************************************************************


(二)struts.xml文件
//**************************************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.objectFactory" value="spring"></constant>

<package name="Paging" extends="struts-default">

  <action name="list" class="listAction" method="list" >
   <result name="input">index.jsp</result>
   <result name="success">/list.jsp</result>
  </action>
 
  <action name="edit" class="listAction" method="edit">
   <result name="success">/update.jsp</result>
  </action>
 
  <action name="update" class="listAction" method="update">
   <result type="redirect">list.action</result>
  </action>
 
  <action name="add" class="listAction" method="add">
   <result type="redirect">list.action</result>
  </action>
 
  <action name="delete" class="listAction" method="delete">
   <result type="redirect">/list.action</result>
  </action>

</package>

</struts>
//**************************************************************************************************

(三)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">

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

<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
  jdbc:mysql://localhost:2008/test
</property>
<property name="dialect">
  org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">
  mysql_Paging
</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">
  com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="cn/paging/model/Member.hbm.xml" />

</session-factory>

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


(四)web.xml文件
//**************************************************************************************************
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<filter>
  <filter-name>hibernateFilter</filter-name>
  <filter-class>
   org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  </filter-class>
</filter>

<filter>
  <filter-name>struts2</filter-name>
  <filter-class>
   org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>
</filter>

<filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>*.action</url-pattern>
</filter-mapping>

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>

<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
//**************************************************************************************************

三。看数据库mysql,表名Member
//**************************************************************************************************
create table Member
(
id int(11) not null auto_increment primary key,
name varchar(20),
password varchar(100)
)
//**************************************************************************************************

四。看主要代码(以下以包的形式逐一列出)
1.cn.paging.action
ListMemberAction.java
//**************************************************************************************************
package cn.paging.action;

import java.util.Iterator;

import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


import com.opensymphony.xwork2.ActionSupport;

import cn.paging.bean.PageBean;
import cn.paging.model.Member;
import cn.paging.service.MemberService;
import cn.paging.util.HibernateUtils;

public class ListMemberAction extends ActionSupport
{
private MemberService memberService;
private Member member;
private String id;
private static int myId;//keep the id from the link

public void setMemberService(MemberService memberService)
{
  this.memberService = memberService;
}

public Member getMember()
{
  return member;
}

public void setMember(Member member)
{
  this.member = member;
}

private int page; //initial page,default page=1

private PageBean pageBean; //pages information about(all records,list records in per page...)

public int getPage()
{
  return page;
}

public void setPage(int page)
{
  this.page = page;
}

public PageBean getPageBean()
{
  return pageBean;
}

public void setPageBean(PageBean pageBean)
{
  this.pageBean = pageBean;
}

public String getId()
{
  return id;
}

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

/**
  * list paged records
  * @return
  * @throws Exception
  */
public String list() throws Exception
{
  System.out.println("page="+page);
  //list the current page's records,3 records in a page
  this.pageBean = memberService.queryForPage(3, page);
  return SUCCESS;
}

/**
  * edit member for update
  * @return string
  * @throws Exception
  */
public String edit() throws Exception
{
  myId=Integer.parseInt(id);
  member = (Member)memberService.edit(Integer.parseInt(id));
 
  return SUCCESS;
}

/**
  * update member
  * @return string
  * @throws Exception
  */
public String update() throws Exception
{
  Member m = new Member();
  m.setId(myId);
  m.setName(member.getName());
  m.setPassword(member.getPassword());
  memberService.update(m);
  return SUCCESS;
}

/**
  * add member
  * @return string
  * @throws Exception
  */
public String add() throws Exception
{
  Member m = new Member();
  m.setName(member.getName());
  m.setPassword(member.getPassword());
  memberService.add(m);
  return SUCCESS;
}



/**
  * delete member
  * @return string
  * @throws Exception
  */
public String delete()throws Exception
{
  memberService.delete(Integer.parseInt(id));
  return SUCCESS;
 
}




}

//**************************************************************************************************

2.cn.paging.bean
PageBean.java
//**************************************************************************************************
package cn.paging.bean;

import java.util.List;

public class PageBean
{

private List list;

private int allRow; //all records

private int totalPage;

private int currentPage;

private int pageSize; //records in per page

private boolean isFirstPage;

private boolean isLastPage;

private boolean hasPreviousPage;

private boolean hasNextPage;

public List getList()
{
  return list;
}

public void setList(List list)
{
  this.list = list;
}

public int getAllRow()
{
  return allRow;
}

public void setAllRow(int allRow)
{
  this.allRow = allRow;
}

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;
}

public int getPageSize()
{
  return pageSize;
}

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


/**
  * initial paging information
  */
public void init()
{
  this.isFirstPage = isFirstPage();
  this.isLastPage = isLastPage();
  this.hasPreviousPage = isHasPreviousPage();
  this.hasNextPage = isHasNextPage();
}

public boolean isFirstPage()
{
  return currentPage == 1;
}

public boolean isLastPage()
{
  return currentPage == totalPage;
}

public boolean isHasPreviousPage()
{
  return currentPage != 1;
}

public boolean isHasNextPage()
{
  return currentPage != totalPage;
}


public static int countTotalPage(final int pageSize, final int allRow)
{
  int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow
    / pageSize + 1;
  return totalPage;
}


public static int countOffset(final int pageSize, final int currentPage)
{
  final int offset = pageSize * (currentPage - 1);
  return offset;
}


public static int countCurrentPage(int page)
{
 
  final int curPage = (page == 0 ? 1 : page);
  return curPage;
}
}
//**************************************************************************************************

3.cn.paging.dao
MemberDao.java
//**************************************************************************************************
package cn.paging.dao;

import java.util.List;

public interface MemberDao
{

/**
  * query for paging
  * @param hql (string expression)
  * @return records
  */
public List queryForPage(final String hql,final int offset,final int length);

/**
  * query all records
  * @param hql (string expression)
  * @return total records
  */
public int getAllRowCount(String hql);

/**
  * update record
  * @param o (object that mapping your class's name in model)
  *
  */
public void update(Object o);

/**
  * add record
  * @param o
  */
public void add(Object o);

/**
  * delete record
  *
  * @param id (delete record by id)
  */
public void delete(int id);

/**
  * edit record for update
  * @param id (edit it by id)
  * @return object
  */
public Object edit(int id);

}

//**************************************************************************************************

4.cn.paging.dao.impl
MemberDaoImpl.java
//**************************************************************************************************
package cn.paging.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.paging.dao.MemberDao;
import cn.paging.model.Member;
import cn.paging.util.HibernateUtils;

public class MemberDaoImpl extends HibernateDaoSupport implements MemberDao
{

/**
  * query for paging
  * @param hql (string expression)
  * @param offset (first record)
  * @param length (the quantity of record in per page)
  * @return list (for paging in a page)
  */
public List queryForPage(final String hql, final int offset,
   final int length)
{
  Query query = HibernateUtils.getSession().createQuery(hql);
  query.setFirstResult(offset);
  query.setMaxResults(length);
  List list = query.list();
  return list;

}

/**
  * query all records
  * @return the number of total records
  */
public int getAllRowCount(String hql)
{
 
  int result = 0;

  result = HibernateUtils.getSession().createQuery(hql).list().size();

  return result;
}

/**
  * edit for update
  * @param id (edit by id)
  */
public Object edit(int id)
{
  System.out.println("memberdaoimpl edit id=" + id);

  Query query = HibernateUtils.getSession().createQuery(
    "from Member m where m.id=:id ").setInteger("id", id);

  return query.iterate().next();

}


/**
  * update record by object
  * @param o (add record by object)
  */
public void update(Object o)
{

  Session session = HibernateUtils.getSession();

  Transaction tx = null;
  try
  {
   tx = session.beginTransaction();
   session.update(o);
   Member m = (Member) o;
   tx.commit();
   System.out.println("memberDoaImpl updateOrSave Object.name="
     + m.getName());
   System.out.println("memberDoaImpl updateOrSave Object.password="
     + m.getPassword());
   System.out.println("memberDoaImpl updateOrSave Object.id="
     + m.getId());
  }
  catch (HibernateException e)
  {
   e.printStackTrace();
   tx.rollback();
  }
  finally
  {
   HibernateUtils.closeSession(HibernateUtils.getSession());
  }

  System.out.println("memberDoaImpl updateOrSave success");
}

/**
  * add record
  * @param o (add record by object)
  */
public void add(Object o)
{
  Session session = HibernateUtils.getSession();
  Transaction tx = null;
  try
  {
   tx = session.beginTransaction();
   session.save(o);
   Member m = (Member) o;
   tx.commit();
   System.out.println("memberDoaImpl updateOrSave Object.name="
     + m.getName());
   System.out.println("memberDoaImpl updateOrSave Object.password="
     + m.getPassword());
   System.out.println("memberDoaImpl updateOrSave Object.id="
     + m.getId());
  }
  catch (HibernateException e)
  {
   e.printStackTrace();
   tx.rollback();
  }
  finally
  {
   HibernateUtils.closeSession(HibernateUtils.getSession());
  }

  System.out.println("memberDoaImpl add success");
 
}

/**
  * delete record
  * @param id (delete record by id)
  */
public void delete(int id)
{

  Session session = HibernateUtils.getSession();
  Transaction tx = null;
  try
  {
   tx = session.beginTransaction();
   //   String hql="delete from Member m where m.id=:id";
   //   int queryDelete=HibernateUtils.getSession().createQuery("delete from Member m where m.id=:id")
   //          .setInteger("id", id)
   //          .executeUpdate();

   Member m = (Member) session.get(Member.class, id);
   session.delete(m);
   tx.commit();
   System.out.println("MemberDaoImpl delete id=" + id);
  }
  catch (HibernateException e)
  {
   e.printStackTrace();
   tx.rollback();
  }
  finally
  {
   HibernateUtils.closeSession(HibernateUtils.getSession());
  }
  System.out.println("memberDoaImpl  delete");
}

}
//**************************************************************************************************

5.cn.paging.model
Member.java
//**************************************************************************************************
package cn.paging.model;

public class Member
{
private int id;

private String name;

private String password;

public int getId()
{
  return id;
}

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

public String getName()
{
  return name;
}

public void setName(String name)
{
  this.name = name;
}

public String getPassword()
{
  return password;
}

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

//**************************************************************************************************
Member.hbm.xml
//**************************************************************************************************
<?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">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="cn.paging.model.Member" table="member" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20" not-null="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="100" />
        </property>
    </class>
</hibernate-mapping>
//**************************************************************************************************

6. cn.paging.service
MemberService.java

//**************************************************************************************************
package cn.paging.service;

import cn.paging.bean.PageBean;

public interface MemberService
{

public PageBean queryForPage(int pageSize, int currentPage);

public Object edit(int id);

public void update(Object o);

public void add(Object o);

public void delete(int id);

}
//**************************************************************************************************

7.cn.paging.service.impl
MemberServiceImpl.java
//**************************************************************************************************
package cn.paging.service.impl;

import java.util.List;

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

import cn.paging.bean.PageBean;
import cn.paging.dao.MemberDao;
import cn.paging.model.Member;
import cn.paging.service.MemberService;
import cn.paging.util.HibernateUtils;

public class MemberServiceImpl implements MemberService
{

private MemberDao memberDao;

public void setMemberDao(MemberDao memberDao)
{
  this.memberDao = memberDao;
}

/** */
/**
  * query for paging
  *
  * @param currentPage
  *           
  * @param pageSize (the quantity of per page)
  *           
  * @return page information
  */
public PageBean queryForPage(int pageSize, int page)
{

  final String hql = "from Member ";
  int allRow = memberDao.getAllRowCount(hql); //all records
  int totalPage = PageBean.countTotalPage(pageSize, allRow); // all pages
  final int offset = PageBean.countOffset(pageSize, page); // the start record in a page
  final int length = pageSize; // quantity of records in a page
  final int currentPage = PageBean.countCurrentPage(page);
  List<Member> list = memberDao.queryForPage(hql,offset,length);

  // keep the page information in pagaBean so that they may list in the list.jsp
  PageBean pageBean = new PageBean();
  pageBean.setPageSize(pageSize);
  pageBean.setCurrentPage(currentPage);
  pageBean.setAllRow(allRow);
  pageBean.setTotalPage(totalPage);
  pageBean.setList(list);
  pageBean.init();//default deploy,page=1
  return pageBean;
}

public void delete(int id)
{
  memberDao.delete(id);
}

public void update(Object o)
{
  memberDao.update(o);
}

public void add(Object o)
{
  memberDao.add(o);
 
}
public Object edit(int id)
{
 
  return memberDao.edit(id);
}


}

//**************************************************************************************************

8.cn.paging.util
HibernateUtils.java
//**************************************************************************************************
package cn.paging.util;

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

public class HibernateUtils
{
private static SessionFactory sessionFactory;

static
{
  try
  {
   Configuration cfg = new Configuration().configure();
  
   sessionFactory=cfg.buildSessionFactory();
  
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
}

public static SessionFactory getSessionFactory()
{
  return sessionFactory;
}

public static void setSessionFactory(SessionFactory sessionFactory)
{
  HibernateUtils.sessionFactory = sessionFactory;
}

public static Session getSession()
{
  return sessionFactory.openSession();
}

public static void closeSession(Session session)
{
  if(null != session)
  {
   if(session.isOpen())
   {
    session.close();
   }
  }
}



}

//**************************************************************************************************


五.最好加上此log4.properties文件,有助于找错
//**************************************************************************************************
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${petstore.root}/WEB-INF/petstore.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

//**************************************************************************************************

六。看jsp文件
1.indext.jsp
//**************************************************************************************************
<% response.sendRedirect(request.getContextPath() + "/list.action?"); %>
//**************************************************************************************************

2.list.jsp
//**************************************************************************************************
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>Member List</title>
  <style type="text/css">
        table {
            border: 1px solid black;
            border-collapse: collapse;
        }
       
        table thead tr th {
            border: 1px solid black;
            padding: 3px;
            background-color: #cccccc;
        }
       
        table tbody tr td {
            border: 1px solid black;
            padding: 3px;
        }
    </style>
    <script type="text/javascript">
     function doDelete()
     {
      var msg = "您真的确定要删除吗?\n\n请确认!";
   if (confirm(msg)==true)
   {
    return true;
   }
   else
   {
    return false;
   }

     }
    
     function goTo(str,allPages)
     {
     
      var vArr = str.match(/^[0-9]+$/);
  
   if (vArr == null)
   {
    alert("只能输入数字!范围在 1-"+allPages+" 之间");
    document.all.goToPage.value="输入跳转页数";
    return false;
   }
   else
   {
    if(str>0 && str <=allPages)
    {
     window.location.href ="list.action?&page="+str;
    }
    else
    {
     alert("只能输入数字!范围在 1-"+allPages+" 之间");
     document.all.goToPage.value="输入跳转页数";
    }
    return true;
   }
     }
    
     function ok(str,pages)
     {
      alert(str+",pages="+pages);
     
     }
    
    </script>
</head>

<body>
  <table cellspacing="1" width="800px" theme="simple">
   <thead>
    <tr>
     <th width="300px">
      NAME
     </th>
     <th width="300px">
      PASSWORD
     </th>
     <th width="200px">
      OPERATE
     </th>
    </tr>
   </thead>
   <tbody>
    <s:iterator value="pageBean.list">
     <tr>
      <td>
       <s:property value="name" />
      </td>
      <td>
       <s:property value="password" />
      </td>
      <td>
       <a href='<s:url action="edit"><s:param name="id" value="id" /></s:url>'>Update</a>
       
       <a href='<s:url action="delete"><s:param name="id" value="id" /></s:url>' onclick="return doDelete()">
        delete
       </a>
      
       
      </td>
     </tr>
    </s:iterator>
   </tbody>
  </table>
  <tr>
   <td>
    共
    <s:property value="pageBean.allRow" />
    条记录 共
    <s:property value="pageBean.totalPage" />
    页 当前第
    <s:property value="pageBean.currentPage" />
    页



    <s:if test="%{pageBean.currentPage == 1}">
             第一页 上一页
          </s:if>
    <s:else>
     <a href="list.action?page=1">第一页</a>
     <a
      href="list.action?page=<s:property value="%{pageBean.currentPage-1}"/>">上一页</a>
    </s:else>
    <s:if test="%{pageBean.currentPage != pageBean.totalPage}">
     <a
      href="list.action?page=<s:property value="%{pageBean.currentPage+1}"/>">下一页</a>
     <a href="list.action?page=<s:property value="pageBean.totalPage"/>">最后一页</a>
    
    </s:if>
    <s:else>
              下一页 最后一页
           </s:else>
   </td>
  </tr>
  <s:textfield name="goToPage" value="输入跳转页数" label="GoTo" onchange='goTo(this.value,%{pageBean.totalPage})'></s:textfield>

  <a href="update.jsp?">添加</a>
</body>
</html>
//**************************************************************************************************

3.update.jsp
//**************************************************************************************************
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Operation</title>
</head>
<body>
  <h2>
   <s:if test="member == null">
            Add Member
             <s:form action="add">
     <s:textfield name="member.name" label="Name" />
     <s:textfield name="member.password" label="Password" />
     <s:submit />
    </s:form>
   </s:if>
   <s:else>
            Update Member
             <s:form action="update">
     <s:textfield name="member.name" label="Name" />
     <s:textfield name="member.password" label="Password" />
     <s:submit />
    </s:form>
   </s:else>
  </h2>

</body>
</html>



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/luanmad/archive/2008/12/29/3636421.aspx

你可能感兴趣的:(spring,Hibernate,xml,log4j,struts)