读书人

十六 Spring2.5+Hibernate3.3+Struts1

发布时间: 2012-11-11 10:07:57 作者: rapoo

十六 Spring2.5+Hibernate3.3+Struts1.3整合开发

十六 Spring2.5+Hibernate3.3+Struts1.3整合开发整合这几个框架,并不是一下子全部配置好的,一般来说先配置spring,然后整合hibernate,最后加入struts。第一步 引入jar 引入spring的jarspring的核心jardist\spring.jar//整合struts1用到的jardist\modules\spring-webmvc-struts.jarlib\jakarta-commons\commons-logging.jar、//数据源支持的jarcommons-dbcp.jar、commons-pool.jar//aop支持的jarlib\aspectj\aspectjweaver.jar、aspectjrt.jarlib\cglib\cglib-nodep-2.1_3.jar//注解用到的jarlib\j2ee\common-annotations.jar//打印日志用到的jarlib\log4j\log4j-1.2.15.jar2 引入hibernate3的jar包 3 配置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:context="http://www.springframework.org/schema/context"       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.5.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 启动依赖注入 注解方式--> <context:annotation-config/> <!--配置数据源--> <bean id="dataSource" destroy-method="close">    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"/>    <property name="username" value="root"/>    <property name="password" value="root"/>     <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/>  </bean>  <!--配置sessionFactory--><bean id="sessionFactory" ref="dataSource"/> <property name="mappingResources">    <list>      <value>cn/itcast/bean/Person.hbm.xml</value>    </list> </property>     <property name="hibernateProperties">    <value>        hibernate.dialect=org.hibernate.dialect.MySQL5Dialect        hibernate.hbm2ddl.auto=update        hibernate.show_sql=false        hibernate.format_sql=false      </value>     </property></bean><!--配置事务管理器容器--><bean id="txManager" ref="sessionFactory"/></bean><!-- 启动事务注解管理方式 --><tx:annotation-driven transaction-manager="txManager"/><!--配置bean--><bean id="personService" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的--><!--classpath:前缀指定从类路径下寻找  --><!--作用:让web容器去初始化spring--><context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:beans.xml</param-value></context-param><!-- 对Spring容器进行实例化 --><listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置struts的web框架--><servlet><servlet-name>struts</servlet-name><servlet-class>org.apache.struts.action.ActionServlet</servlet-class><init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value></init-param><load-on-startup>0</load-on-startup></servlet><servlet-mapping><servlet-name>struts</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  </web-app>现在我们来新建一个action package cn.itcast.web;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import cn.itcast.service.PersonService;public class PersonAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {    //得到spring容器实例WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());PersonService personservice=(PersonService)ctx.getBean("personService");request.setAttribute("persons", personservice.getPersons());return mapping.findForward("list");}}配置action struts-config.xml<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"        "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config><action-mappings><action path="/person/list" type="cn.itcast.web.PersonAction" validate="false"><forward name="list" path="/WEB-INF/page/personlist.jsp"></forward></action></action-mappings></struts-config>测试下是否通过即可如果action没有交给spring管理时,我们通过下面语句获取spring容器实例WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());把action交给spring管理后,我们可以使用依赖注入在action中注入业务层的bean。确保action的path属性值与bean的名称相同。<action path="/person/list" ...></action>Spring 配置:<bean name="/person/list" value="org.springframework.web.struts.DelegatingRequestProcessor"/></controller> 具体步骤如下:将action交给Spring进行管理,并把相应的service服务依赖注入到Action中第一步:将Action注册到spring 中 并设置其名称 名称与struts中的path名称一致spring中的配置 <bean name="/person/list"  validate="false"><forward name="list" path="/WEB-INF/page/personlist.jsp"></forward></action></action-mappings>发现action少了type了呢,这是为下一步做好配置,因为交给spring去管理后,struts中的spring控制器会在spring中寻找spring中的配置的bean名称为path名称的bean 第二步 在struts-config.xml中加入spring的控制器 用于管理action 这时action就交给了spring进行管理了<!-- 配置spring的控制器 --><controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/></controller> 第三步:将服务依赖注入到action中 采用注解方式Resource现在来看action package cn.itcast.web;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import cn.itcast.service.PersonService;public class PersonAction extends Action {   @Resource PersonService personservice;@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {    //得到spring容器实例//WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext//(this.getServlet().getServletContext());//PersonService personservice=(PersonService)ctx.getBean("personService");request.setAttribute("persons", personservice.getPersons());return mapping.findForward("list");}}分析:发现不需要WebApplicationContext来获得spring的容器实例了这时ssh框架就已经完成了现在我们还要去配置二级缓存第一步 加入缓存的jar包 当前我们使用ehcache这个第三方框架  lib\optional\ehcache-1.2.3.jar第二步 配置 在spring中的sessionFactory去配置    <!-- 配置二级缓存 -->        hibernate.cache.use_second_level_cache=true        <!-- 是否使用查询缓存 -->               hibernate.cache.use_query_cache=false               <!-- 配置使用缓存的驱动类 -->            hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider  第三步 在src目录下加入缓存第三方框架配置文件 Ehcache默认的配置文件ehcache.xml(放在类路径下)<ehcache>    <diskStore path="D:\cache"/>    <defaultCache  maxElementsInMemory="1000“  eternal="false“ overflowToDisk="true"        timeToIdleSeconds="120"        timeToLiveSeconds="180"        diskPersistent="false"        diskExpiryThreadIntervalSeconds="60"/><cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/></ehcache>    defaultCache节点为缺省的缓存策略     maxElementsInMemory 内存中最大允许存在的对象数量     eternal 设置缓存中的对象是否永远不过期     overflowToDisk 把溢出的对象存放到硬盘上     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉     timeToLiveSeconds 指定缓存对象总的存活时间     diskPersistent 当jvm结束是是否持久化对象     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间<diskStore path="D:\cache"/> 表示的是缓存存放的硬盘路径第四步:为指定的类注册缓存,并指定其缓存策略 缓存的区域名 这个区域是用来配置缓存的对象,这个对象就是当前配置的这个实体的对象数据方法:在实体bean的xml映射文件中配置 Person.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"><hibernate-mapping package="cn.itcast.bean">    <!--配置二级缓存-->    <class name="Person" table="person">    <cache usage="read-only" region="cn.itcast.bean."/>        <id name="id">            <generator length="10" not-null="true"/>    </class></hibernate-mapping>现在我们来对指定后的缓存区域进行缓存的配置配置方法 在缓存框架的配置文件(ehcache.xml)进行配置<?xml version="1.0" encoding="UTF-8"?><!--     defaultCache节点为缺省的缓存策略     maxElementsInMemory 内存中最大允许存在的对象数量     eternal 设置缓存中的对象是否永远不过期     overflowToDisk 把溢出的对象存放到硬盘上     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉     timeToLiveSeconds 指定缓存对象总的存活时间     diskPersistent 当jvm结束是是否持久化对象     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间 --><ehcache>    <diskStore path="D:\cache"/>    <defaultCache  maxElementsInMemory="1000" eternal="false" overflowToDisk="true"        timeToIdleSeconds="120"        timeToLiveSeconds="180"        diskPersistent="false"        diskExpiryThreadIntervalSeconds="60"/><!--给缓存区域是cn.itcast.bean.Person的指定特殊缓存配置,如果不指定将运用上述公共的缓存配置--><cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/></ehcache>现在缓存的配置就已经好了 现在我们来测试 怎么测试呢 查询--关闭---查询 如果能再第二次查询能过查询到数据就说明缓存配置成功 当前我们只能对单个的数据进行查询配置成功如果对list的集合类型有多条数据的查询当前的配置是不能成功的只能对单条的数据进行查询,能运用到缓存 如果要findall() list() Iterator() createCriteria() createQuery()等方法获得数据结果集得话,需要设置hibernate.cache.use_query true才行 并且需要查询缓存,还需要在使用Query或者criteria()时设置其setCacheable(true)属性现在来看spring配置文件 <?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:context="http://www.springframework.org/schema/context"       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.5.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 启动依赖注入 --> <context:annotation-config/> <bean id="dataSource" destroy-method="close">    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"/>    <property name="username" value="root"/>    <property name="password" value="root"/>     <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/>  </bean>  <bean id="sessionFactory" ref="dataSource"/> <property name="mappingResources">    <list>      <value>cn/itcast/bean/Person.hbm.xml</value>    </list> </property>     <property name="hibernateProperties">    <value>        hibernate.dialect=org.hibernate.dialect.MySQL5Dialect        hibernate.hbm2ddl.auto=update        hibernate.show_sql=false        hibernate.format_sql=false        <!-- 配置二级缓存 -->        hibernate.cache.use_second_level_cache=true        <!-- 是否使用查询缓存 当前配置上查询缓存 ,但是查询缓存的命中率并不是很高,所以没有必要为其配置 当前是设为true是配置上查询缓存-->               hibernate.cache.use_query_cache=true               <!-- 配置使用缓存的驱动类 -->            hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider        </value>     </property></bean><bean id="txManager" ref="sessionFactory"/></bean><!-- 启动事务注解管理方式 --><tx:annotation-driven transaction-manager="txManager"/><bean id="personService" type="cn.itcast.formbean.PersonForm"/></form-beans ><global-forwards><forward name="message" path="/WEB-INF/page/message.jsp"></forward></global-forwards><action path="/person/pmessage" validate="false" parameter="method" scope="request" name="PersonForm"></action>将当前的action交给spring管理<bean name="/person/pmessage" prefix="html" %>在页面中添加一个表单  <html:form action="/person/pmessage" method="post">  <html:text property="name"/>  <html:hidden property="method"  value="add"/>  <html:submit value="提交 "/>  </html:form>现在来建一个message.jsp <body>    ${message }  </body>现在在浏览器输入测试http://localhost:8808/SSH/Spring2.5+Hibernate3.3+Struts1.3的数据录入乱码解决在web.xml中加入spring的乱码解决struts1的问题<filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>使用spring解决hibernate因session关闭导致的延迟加载例外问题。方法 在web.xml中添加<filter>        <filter-name>OpenSessionInViewFilter</filter-name>        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping>        <filter-name>OpenSessionInViewFilter</filter-name>        <url-pattern>/*</url-pattern></filter-mapping>现在来看完整的web.xml配置文件<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 --><context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:beans.xml</param-value></context-param><!-- 对Spring容器进行实例化 --><listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 加入spring的filter 用于乱码解决--><filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 使用spring解决hibernate因session关闭导致的延迟加载例外 --><filter>        <filter-name>OpenSessionInViewFilter</filter-name>        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping>        <filter-name>OpenSessionInViewFilter</filter-name>        <url-pattern>/*</url-pattern></filter-mapping><!-- 配置struts的web框架--><servlet><servlet-name>struts</servlet-name><servlet-class>org.apache.struts.action.ActionServlet</servlet-class><init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value></init-param><load-on-startup>0</load-on-startup></servlet><servlet-mapping><servlet-name>struts</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  </web-app>spring的配置文件 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:context="http://www.springframework.org/schema/context"       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.5.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 启动依赖注入 --> <context:annotation-config/> <bean id="dataSource" destroy-method="close">    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"/>    <property name="username" value="root"/>    <property name="password" value="root"/>     <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/>  </bean>  <bean id="sessionFactory" ref="dataSource"/> <property name="mappingResources">    <list>      <value>cn/itcast/bean/Person.hbm.xml</value>    </list> </property>     <property name="hibernateProperties">    <value>        hibernate.dialect=org.hibernate.dialect.MySQL5Dialect        hibernate.hbm2ddl.auto=update        hibernate.show_sql=false        hibernate.format_sql=false        <!-- 配置二级缓存 -->        hibernate.cache.use_second_level_cache=true        <!-- 是否使用查询缓存 -->               hibernate.cache.use_query_cache=true               <!-- 配置使用缓存的驱动类 -->            hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider        </value>     </property></bean><bean id="txManager" ref="sessionFactory"/></bean><!-- 启动事务注解管理方式 --><tx:annotation-driven transaction-manager="txManager"/><bean id="personService" encoding="UTF-8"?><!--     defaultCache节点为缺省的缓存策略     maxElementsInMemory 内存中最大允许存在的对象数量     eternal 设置缓存中的对象是否永远不过期     overflowToDisk 把溢出的对象存放到硬盘上     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉     timeToLiveSeconds 指定缓存对象总的存活时间     diskPersistent 当jvm结束是是否持久化对象     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间 --><ehcache>    <diskStore path="D:\cache"/>    <defaultCache  maxElementsInMemory="1000" eternal="false" overflowToDisk="true"        timeToIdleSeconds="120"        timeToLiveSeconds="180"        diskPersistent="false"        diskExpiryThreadIntervalSeconds="60"/><cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/></ehcache>struts-config.xml配置文件 <?xml version="1.0" encoding="utf-8" ?><!DOCTYPE struts-config PUBLIC          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"          "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config><form-beans><form-bean name="PersonForm" type="cn.itcast.formbean.PersonForm"/></form-beans ><global-forwards><forward name="message" path="/WEB-INF/page/message.jsp"></forward></global-forwards><action-mappings><action path="/person/list"  validate="false"><forward name="list" path="/WEB-INF/page/personlist.jsp"></forward></action><action path="/person/pmessage" validate="false" parameter="method" scope="request" name="PersonForm"></action></action-mappings><!-- 配置spring的控制器 --><controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/></controller> </struts-config>hibernate的实体beans.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"><hibernate-mapping package="cn.itcast.bean">    <class name="Person" table="person">    <cache usage="read-only" region="cn.itcast.bean.Person"/>        <id name="id">            <generator length="10" not-null="true"/>    </class></hibernate-mapping>

?

读书人网 >编程

热点推荐