花了一下午,终于将struts2.18+hibernate3.5.6+spring2.5.5进行整合,完成功能:在Oracle数据库的TCourse表中插入一条数据。
Ⅰ,整合流程:web启动————》spring与struts2启动————》hibernate启动
一,web.xml文件中配置spring与struts2;
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
index.jsp
说明:
1,spring容器加载:
spring容器是以监听器的形式整合到web服务器中,伴随服务器的启动,容器也启动并创建相应的bean,其中:单例的bean会被创建(如:CourseDaoImpl,CourseServiceImpl等),多例的不会创建(如:struts2的action——CourseAction).
contextConfigLocation
classpath:applicationContext.xml
这段代码表示加载spring的配置文件。
2,struts2加载:
struts2的加载是通过过滤器实现的,过滤器原理,没啥好说的。
二,struts2与spring的集合:
1,引入一个struts2提供的包:struts2-spring-plugin-2.1.8.1.jar。
2,原理: 如果包解压开会看见一个 “struts-plugin.xml”的文件,如下
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
说明:只需解释两行关键代码:
三,spring与hibernate的整合:通过spring配置文件---->得到hibernate的SessionFactory---->得到HibernateTemplate
1,spring配置文件:
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
classpath:hibernate.cfg.xml
说明:
1,1 dataSoure对象----》取得数据库连接;
dataSoure对象的类型BasicDataSource是Java.sql.DataSource接口的实现,实现此接口就可以得到一个数据库连接。
1,2 sessionFactory对象----》取得hibernate的sessionFactory;
类型为:org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean 表示支持annotation,如果没有annotation可以用:
org.springframework.orm.hibernate3.LocalSessionFactoryBean
即:
1,3 classpath:hibernate.cfg.xml---->加载hibernate的配置文件
四,项目文件结构
Ⅱ,常见问题
1,java.lang.NoClassDefFoundError: javax/persistence/EntityListeners
在使用Hibernate3的时候,发现程序编译好了,在运行时总是抛出java.lang.NoClassDefFoundError: javax/persistence/EntityListeners异常,经查找是因为缺少ejb3-persistence.jar包。
解决方法:类库中加入ejb3-persistence.jar。
2,Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/Cacheable
少了包
解决方案:加入hibernate-jpa-2.0-api-1.0.1.Final.jar
3,class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
hibernate3.5中的hibernate3.0包,已经包涵了hibernate-annotations,hibernate-commons-annotations.jar,commons-collections 这三个包,
解决方法:要去掉commons-collections 一个包或者hibernate-annotations,hibernate-commons-annotations.jar两个包。
附件:所需包