- 浏览: 102892 次
- 性别:
- 来自: 福建
文章分类
最新评论
-
kely39:
一语中的
配置Tomcat 中文字符集问题 -
hbdxwz0319:
顶,找了很久解决办法,终于找到了
配置Tomcat 中文字符集问题 -
chi8wenyu:
受用了!!
一个完整的struts2+spring+hibernate+分页实例 -
GlennZhou:
...
不再限于页面脚本 JavaScript挺入服务器端开发语言序列
一个完整的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
前段时间,一直在为配置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
相关推荐
总的来说,这个"Struts2+Spring2+Hibernate3注册查询搜索分页实例"是一个很好的学习资源,涵盖了Java Web开发中的基础和核心部分。通过学习这个实例,开发者不仅可以掌握三大框架的基本用法,还能了解到如何将它们...
本例主要是实现了struts2+spring3+hibernate3的 基本框架搭建的注册登录,以及用户增删改查,适于初学者学习。 包括:注册 登录功能 分页的实现 前端校验 验证码的实现 注册时有ajax 校验,登录时 后台从数据库...
这是一个struts2+hibernate+spring整合的实例,带有分页功能,希望对刚接触struts2的朋友有些帮助。spring2.0,hibernate3.1分页用的是自字义标签,不要少了这个包standard.jar
这个项目展示了如何将这三个框架整合起来,实现一个完整的书籍管理应用,包括书籍的增加、删除、修改和查询功能,并且包含了分页展示。下面我们将深入探讨这些技术及其在项目中的应用。 首先,Struts1.3是MVC...
在实际开发中,一个可能的流程是这样的:用户通过Struts2发起报表请求,Struts2 Action接收到请求后,利用Spring的依赖注入获取到需要的Service,Service通过Hibernate从数据库获取数据,然后使用Apache POI将数据...
通过理解Struts、Spring和Hibernate的原理及其相互关系,开发者可以将它们高效地组合起来,形成一个以Spring为核心,Struts为表现层,Hibernate为数据访问层的架构。这个案例的实现有助于深入理解SSH整合的实际运用...
【Struts2+Spring2+Hibernate3】是一个经典的Java企业级开发组合,常用于构建复杂的Web应用程序,如图书管理系统。这个组合充分利用了每个框架的核心优势,以提高开发效率和代码的可维护性。 **Struts2** 是一个MVC...
一个Struts1.2+Spring2.5+Hibernate3.2+Jmesa2.4.3+JmesaTag实现的强大分页控件例子 里 面有action实现分页和标签实现分页2个例子 action实现的分页 包括了表头排序,导出为PDF,TXT, excel等格式 jar包和数据库...
Struts、Spring 和 Hibernate 是Java Web开发中三个非常重要的开源框架,它们共同构成了所谓的SSH(Struts + Spring + Hibernate)框架。这篇描述提到的是一个基于SSH框架实现的网上购物车系统,下面将详细介绍这三...
Struts 2、Hibernate 和 Spring 是 Java Web 开发中的三个重要框架,它们组合在一起形成了一个强大的后端开发架构。这个基于 Struts 2+Hibernate+Spring 的论坛系统源码提供了学习和理解这些技术如何协同工作的实例...
### Hibernate+Struts2+Spring 实现分页实例详解 #### 一、概述 在Web应用开发中,分页是一项非常实用且常见的功能。本文将详细介绍如何利用Hibernate、Struts2与Spring三个框架来实现一个完整的分页示例。通过本...
SSH2分页程序,这是实例中的一个重要部分。在处理大量数据时,分页功能是必不可少的。在Hibernate中,可以使用Criteria API或者HQL(Hibernate Query Language)结合Limit和Offset来实现分页查询。而使用注解配置的...
是一个基于struts2+spring+jpa架构的分页实例(带jar包和数据库脚本)还原好数据库,用MyEclipse导入工程,部署到Tomcat就可运行。注:由于资源大小限制,我去掉了spring.jar 和 hibernate3.jar 自己加上,JDK用6.0...
总结,整合Hibernate、Struts2和Spring实现分页功能,涉及的主要步骤包括:定义分页信息类,编写业务逻辑处理分页查询,以及在前端展示分页结果。这不仅提高了用户体验,也使得服务器能够更有效地处理大量数据,避免...
这个实例结合了这些技术,构建了一个完整的Web应用,涵盖了从前端用户交互到后端数据存储的整个流程。Struts2处理HTTP请求,Spring3管理业务逻辑和依赖,Hibernate3负责数据持久化,jQuery提供前端交互,Flexigrid...
总的来说,"新闻发布系统JAVA源码(struts+spring+hibernate)"是一个典型的Java Web企业级应用实例,展示了如何利用成熟的开源框架构建复杂的功能,同时保证了代码的可读性和可维护性。对于学习和理解Java Web开发,...
在这个"Struts2+Spring+Hibernate例子"中,开发者提供了一个完整的示例,旨在展示这三个框架如何协同工作,实现数据的增删改查(CRUD)操作,并且集成了Ext Grid,一个强大的前端展示组件。 **Struts2** 是一个MVC...
综上所述,通过Struts处理用户请求,Spring管理组件和事务,以及Hibernate处理数据库操作,我们可以构建出一个高效、可扩展的分页应用。在这个过程中,Eclipse作为开发环境,提供对Spring和Hibernate的支持,帮助...
总的来说,这个项目提供了在Struts2、Hibernate3和Spring框架下实现分页功能的实例,对于学习和掌握Java Web开发,特别是框架集成与分页技术具有很高的参考价值。通过研究这个项目,开发者可以学习到如何在实际项目...