首页  »   J2EE

【j2ee spring】十、整合SSH框架(3)

网友分享于:2015-04-02  浏览:0次
【j2ee spring】10、整合SSH框架(3)

整合SSH框架(3)

Spring4+hibernate4+Struts2的整合,整合完成后我会把这个项目上传上去,但是我的建议是最好还是自己在自己的电脑上自己整合一下,我不保证一定没问题


前面那个,我们已经基本整合了SSH框架,但是还是有一些小小的瑕疵,

比如:PersonAction.java里面的

//获取实例,方法1  
        ServletContext sc = ServletActionContext.getRequest().getSession().getServletContext();  
        WebApplicationContext wac = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  
        //方法2  
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.  
                                                    getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
          
        if(wac == webApplicationContext)  
        {  
            System.out.println("ok!!!");  
        }  
          
        PersonService personService = (PersonService) wac.getBean("personServiceBean");  

这个,得到ServletContext每次都要写的话,会很麻烦,以后如果获取的bean改了的话,更麻烦,所以这里改进一下,我们用spring的依赖注入的方式获取personService类


1、在PersonAction类里面添加数据成员

@Resource private PersonService personService;		//先按名字注入,如果找不到的话就按类型注入

用注解的方式获取这个类


2、吧action交个spring管理

要用spring的依赖注入的话,我们就得把action交给spring管理了

在spring中添加

<bean id="PersonAction" class="cn.cutter_point.web.action.PersonAction" autowire="byName" />

3、这里我们为了提高数据库的利用效率,这里得设置数据库的二级缓存

spring中修改bean

	<!-- hibernate二级缓存的配置 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	<!-- configuration elided for brevity -->
		<property name="dataSource" ref="myDataSource" />
		<property name="mappingResources">
			<list>	<!-- 映射文件 -->
				<value>cn/cutter_point/bean/Person.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">	<!-- 用来配置hibernate的属性配置 -->
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.hbm2ddl.auto=update  <!--其他取值 create、create-drop、update、validate none -->
				hibernate.show_sql=true
				hibernate.format_sql=true
				<!-- 开启二级缓存功能 -->
				hibernate.cache.use_second_level_cache = true
				hibernate.cache.use_query_cache = false
				hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
		        <!-- hibernate3的二级缓存配置 -->  
		        <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->  
			</value>
		</property>
	</bean>

注意,我使用的是hibernate4,4和3有些不一样,4中没有org.hibernate.cache.EhCacheProvider这个玩意,并且我查找官方文档的时候,坑爹的是文档里面写的还是hibernate.cache.provider_class
这个属性,最后只能问问度娘,才发现官方文档哪里是有错的,没有改过来,但是使用的jar包已经改了。

!!!!!!!!

我勒个擦,感情这个官方文档就是给我们看的,官方的人都是不看的啊

加入几个jar包

这三个一个都别想偷懒了,都得加,我是亲身经历了的,实在懒得动结果一个一个地加,反而更麻烦,早知道管他什么鸡巴毛,一把抓进去好了

4、我们配置一下二级缓存的xml文件

ehcache.xml

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors. All third-party contributions are
  ~ distributed under license by Red Hat Middleware LLC.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
         <!-- 缓存文件存放到硬盘哪里 -->
    <diskStore path="G:\Workspaces\MyEclipse Professional 2014\ssh\cacheFile" />


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
        <!-- 
    defaultCache节点为缺省的缓存策略
     maxElementsInMemory 内存中最大允许存在的对象数量
     eternal 设置缓存中的对象是否永远不过期
     overflowToDisk 把溢出的对象存放到硬盘上
     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
     timeToLiveSeconds 指定缓存对象总的存活时间
     diskPersistent 当jvm结束是是否持久化对象
     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
        
        <!-- 特殊配置项目 -->
     <cache name="cn.cutter_point.bean.Person" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
        overflowToDisk="true" />
        
        
</ehcache>

不要问我为什么英语突然变那么好了,拷贝官方的,你懂的微笑

5、修改一下Person.hbm.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.cutter_point.bean">

<!-- 	<class name="Version">
		<id name="id">
			<generator class="org.hibernate.id.TableHiLoGenerator">
                <param name="table">uid_table</param>
                <param name="column">next_hi_value_column</param>
        	</generator>
		</id>
		<property name="description"/>	
	</class> -->
	
	<class name="Person" table="person">
	<cache usage="read-write" region="cn.cutter_point.bean.Person" />
		<id name="id">
			<generator class="native" />
		</id>
		<property name="name" length="20" not-null="true" />
	</class>

</hibernate-mapping>

6、最后,我们搞一个添加的测试一下二级缓存

	@Test
	public void testGetPerson() 
	{
		Person person = personService.getPerson(2);
		System.out.println(person.getName());
		
		System.out.println("关闭数据区==========");
		try 
		{
			Thread.sleep(1000*15);//15秒
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		} 	
		System.out.println("第二次获取数据");
		person = personService.getPerson(2);
		System.out.println(person.getName()+"   ++++++++++");
		
	}

中间我们关闭MySQL服务



服务已开,时间是2015年3月30日19:07


我们开始测试



接下来我们关闭服务



接下来,我们看看控制台输出


结果是有输出的

2015年3月30日19:11左右,为了截图,我吧那个sleep的时间延长了


其实我们还可以吧那个cache的属性改一下,看看那个缓存文件在哪





相关解决方案

最新解决方案