现在的位置: 首页 > 综合 > 正文

7、ssh整合

2018年02月05日 ⁄ 综合 ⁄ 共 20116字 ⁄ 字号 评论关闭

ssh(struts + spring + hibernate)三大框架配合使用来开发项目,是目前java最流行的开发方式,必须掌握

设计:通过一个实际的案例,来理解整合,使用一个雇员薪资管理系统(CRUD)——增加(Create)、查询(Retrieve)(重新得到数据)、更新(Update)、删除(Delete),每加入一个框架,就测试是否通过。

具体步骤:

创建web项目(ssh一般都是针对web项目来的)

1、先集成spring

2、引入spring开发包,将spring2.5.6的所有JAR包拷贝到web项目的WebRoot/WEB-INF/lib目录下

3、编写applicationContext.xml文件(或者beans.xml),把该文件放在src目录下

4、测试一下spring是否正常--》目前spring可以正常工作。

编写Test测试类,编写一个TestService类,在applicationContext.xml中配置TestService,看看是否调用正常。

5、加入hibernate开发包。同2,将hibernate的所有JAR包拷贝到web项目的WebRoot/WEB-INF/lib目录下

6、因为我们是ssh,所以我们hibernate的核心,就被spring接管了:hibernate.cfg.xml文件、对象映射文件,SessionFactory在spring的文件中配置即可

7、在applicationContext.xml中配置数据源(一个bean,bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" )(可以与hibernate的配置文件hibernate.cfg.xml进行对比)

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
	<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:oracddb" />
	<property name="username" value="scott" />
	<property name="password" value="tiger" />
	<!-- 连接池启动时的初始值 -->
	<property name="initialSize" value="3" />
	<!-- 连接池的最大值 -->
	<property name="maxActive" value="500" />
	<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
	<property name="maxIdle" value="2" />
	<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
	<property name="minIdle" value="1" />
</bean>

目前的配置,还没有优化,后面还有优化动作

8、配置SessionFactory对象(可以与hibernate的配置文件hibernate.cfg.xml进行对比)

<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!-- 设置数据源 -->
	<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
	<!-- 接管了haibernate的对象映射文件 -->
	<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
		<list>
			<value>com/cdtax/hibernate/bean/Person.hbm.xml</value>
		</list>
	</property>
	
	<property name="hibernateProperties">
		<value>
			hibernate.dialect=org.hibernate.dialect.oracleDialect
			hibernate.hbm2ddl.auto=update
			hibernate.show_sql=true
			hibernate.format_sql=true
		</value>
	</property>
</bean>

9、编写domain对象Employee和映射文件Employee.hbm.xml,然后测试spring和hibernate是否可以结合使用。

创建domain对象(域模型对象):

package com.cdtax.domain;

import java.util.Date;

public class Employee
{
	private	Integer id;
	private String name;
	private String email;
	private java.util.Date hiredate;
	private Float salary;
	
	public Employee()
	{
		
	}
	
	public Employee(String name, String email, Date hiredate, Float salary)
	{
		this.name = name;
		this.email = email;
		this.hiredate = hiredate;
		this.salary = salary;
	}
	public Integer getId()
	{
		return id;
	}
	public void setId(Integer id)
	{
		this.id = id;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public String getEmail()
	{
		return email;
	}
	public void setEmail(String email)
	{
		this.email = email;
	}
	public java.util.Date getHiredate()
	{
		return hiredate;
	}
	public void setHiredate(java.util.Date hiredate)
	{
		this.hiredate = hiredate;
	}
	public Float getSalary()
	{
		return salary;
	}
	public void setSalary(Float salary)
	{
		this.salary = salary;
	}
	
	
}

编写对应的映射文件:Employee.hbm.xml,文件的位置与domain对象相同(就是hibernate的对象关系映射文件)

<?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="com.cdtax.domain">
	<class name="Employee" table="employee">
	<!-- 主键策略 -->
	<id name="id" type="java.lang.Integer">
		<generator class="native" /> <!-- 主要有hilo sequence navtive increment uuid identity foreign -->
	</id>
 
 	<!-- 属性与列的映射写法之一 -->
	<property name="name" type="java.lang.String" column="name" length="64" />
	
	<!-- 属性与列的映射写法之一 -->
	<property name="email" type="java.lang.String">
		<column name="email" length="64"></column>
	</property>
	
	<property name="hiredate" type="java.util.Date">
		<column name="hiredate" />
	</property>	
	
	<property name="salary" type="java.lang.Float">
		<column name="salary" />
	</property>
	
	</class>
</hibernate-mapping>

创建一个测试类:

package com.cdtax.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cdtax.domain.Employee;

public class Test
{
	public static void main(String[] args)
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		
//		TestService ts = (TestService) ac.getBean("testService");
//		
//		System.out.println(ts.getName());
		
		//测试与hibernate的结合
		
		SessionFactory sf = (SessionFactory)ac.getBean("sessionFactory");
		
		Session s = sf.openSession();
		
		Employee employee = new Employee("aa","aa@123.com",new java.util.Date(),2345.56f);
		
		Transaction tx = s.beginTransaction();
		s.save(employee);
		tx.commit();
	}
}

修改一下applicationContext.xml配置文件,修改数据源,使用mysql数据库:

<?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: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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<!-- 配置一个testService对象,测试spring集成是否成功用 -->
<bean id="testService"  class="com.cdtax.test.TestService">
	<property name="name" value="小明"></property>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/hibernate" />
	<property name="username" value="root" />
	<property name="password" value="root" />
	<!-- 连接池启动时的初始值 -->
	<property name="initialSize" value="3" />
	<!-- 连接池的最大值 -->
	<property name="maxActive" value="500" />
	<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
	<property name="maxIdle" value="2" />
	<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
	<property name="minIdle" value="1" />
</bean>

<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!-- 设置数据源 -->
	<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
	<!-- 接管了haibernate的对象映射文件 -->
	<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
		<list>
			<value>com/cdtax/domain/Employee.hbm.xml</value>
		</list>
	</property>
	
	<property name="hibernateProperties">
		<value>
			hibernate.dialect=org.hibernate.dialect.MySQLDialect
			hibernate.hbm2ddl.auto=update
			hibernate.show_sql=true
			hibernate.format_sql=true
		</value>
	</property>
</bean>
</beans>

加入mysql的驱动,就是将mysql-connector-java-5.0.8-bin.jar包加入到WebRoot/WEB-INF/lib目录下
然后执行Test测试程序

执行结果:

Hibernate: 
    insert 
    into
        employee
        (name, email, hiredate, salary) 
    values
        (?, ?, ?, ?)

查询数据库,发现新建了表employee,并且插入了一条记录

测试说明spring与hibernate已经可以结合工作了。

10、考虑分层,增加service接口层和service实现层

创建包com.cdtax.service.interfaces和com.cdtax.service.impl包

创建接口:

package com.cdtax.service.interfaces;

import java.util.List;

import com.cdtax.domain.Employee;

public interface EmployeeServiceInter
{
	//声明一些方法
	public void addEmployee(Employee e);
	public List<Employee> showEmployee();
	public void updateEmployee(Employee e);
	//根据id删除雇员
	public void deleteEmployee(java.io.Serializable id);
}

创建实现类:

package com.cdtax.service.impl;

import java.io.Serializable;
import java.util.List;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.cdtax.domain.Employee;
import com.cdtax.service.interfaces.EmployeeServiceInter;

public class EmployeeService implements EmployeeServiceInter
{

	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	public void addEmployee(Employee e)
	{
		Session s = sessionFactory.openSession();
		Transaction tx = s.beginTransaction();
		s.save(e);
		tx.commit();
	}

	public List<Employee> showEmployee()
	{
		// TODO Auto-generated method stub
		return null;
	}

	public void updateEmployee(Employee e)
	{
		// TODO Auto-generated method stub

	}

	public void deleteEmployee(Serializable id)
	{
		// TODO Auto-generated method stub

	}

}

这个实现类中增加了sessionFactory,因为每个方法都要使用到session和事务,然后使用spring进行统一管理,在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: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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<!-- 配置一个testService对象,测试spring集成是否成功用 -->
<bean id="testService"  class="com.cdtax.test.TestService">
	<property name="name" value="小明"></property>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/hibernate" />
	<property name="username" value="root" />
	<property name="password" value="root" />
	<!-- 连接池启动时的初始值 -->
	<property name="initialSize" value="3" />
	<!-- 连接池的最大值 -->
	<property name="maxActive" value="500" />
	<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
	<property name="maxIdle" value="2" />
	<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
	<property name="minIdle" value="1" />
</bean>

<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!-- 设置数据源 -->
	<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
	<!-- 接管了haibernate的对象映射文件 -->
	<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
		<list>
			<value>com/cdtax/domain/Employee.hbm.xml</value>
		</list>
	</property>
	
	<property name="hibernateProperties">
		<value>
			hibernate.dialect=org.hibernate.dialect.MySQLDialect
			hibernate.hbm2ddl.auto=update
			hibernate.show_sql=true
			hibernate.format_sql=true
		</value>
	</property>
</bean>

<!-- 配置EmployeeService对象 -->
<bean id="employeeService" class="com.cdtax.service.impl.EmployeeService">
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

</beans>

注意这里注入的ref=sessionFactory就是上面配置中配置的<!-- 配置会话工厂() -->
修改测试程序:

package com.cdtax.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cdtax.domain.Employee;
import com.cdtax.service.interfaces.EmployeeServiceInter;

public class Test
{
	public static void main(String[] args)
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		
//		TestService ts = (TestService) ac.getBean("testService");
//		
//		System.out.println(ts.getName());
		
		//测试与hibernate的结合,在Test中控制事务
		
//		SessionFactory sf = (SessionFactory)ac.getBean("sessionFactory");
//		
//		Session s = sf.openSession();
//		
//		Employee employee = new Employee("aa","aa@123.com",new java.util.Date(),2345.56f);
//		
//		Transaction tx = s.beginTransaction();
//		s.save(employee);
//		tx.commit();
		
		//添加service层,同时使用spring管理service层bean,在service中控制事务
		EmployeeServiceInter employeeServiceInter = (EmployeeServiceInter)ac.getBean("employeeService");
		
		Employee employee = new Employee("aa111","aa@123.com",new java.util.Date(),2345.56f);
		
		employeeServiceInter.addEmployee(employee);
	}
}

程序执行是成功的,插入一条记录

11、使用事务管理器来统一管理事务,考虑上面的分层代码,在service实现中,就是EmployeeService类中,每个方法都要写一遍事务处理的代码:

Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();

s.xxx();
tx.commit();

我们考虑是否能够将事务抽取出来,就像AOP面向切面编程一样来让spring统一处理呢?答案是肯定的,spring提供了事务管理器,在spring的配置文件中增加如下配置

<!-- 配置事务管理器,统一管理sessionFactory的事务 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="txManager"/>

这样就让org.springframework.orm.hibernate3.HibernateTransactionManager接管了上面的sessionFactory,然后通过启用事务注解,这样,对于程序中带有@Transactional注解的类或方法中的事务就会被纳入管理,实现事务的自动管理。

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: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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<!-- 配置一个testService对象,测试spring集成是否成功用 -->
<bean id="testService"  class="com.cdtax.test.TestService">
	<property name="name" value="小明"></property>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/hibernate" />
	<property name="username" value="root" />
	<property name="password" value="root" />
	<!-- 连接池启动时的初始值 -->
	<property name="initialSize" value="3" />
	<!-- 连接池的最大值 -->
	<property name="maxActive" value="500" />
	<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
	<property name="maxIdle" value="2" />
	<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
	<property name="minIdle" value="1" />
</bean>

<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!-- 设置数据源 -->
	<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
	<!-- 接管了haibernate的对象映射文件 -->
	<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
		<list>
			<value>com/cdtax/domain/Employee.hbm.xml</value>
		</list>
	</property>
	
	<property name="hibernateProperties">
		<value>
			hibernate.dialect=org.hibernate.dialect.MySQLDialect
			hibernate.hbm2ddl.auto=update
			hibernate.show_sql=true
			hibernate.format_sql=true
		</value>
	</property>
</bean>

<!-- 配置EmployeeService对象 -->
<bean id="employeeService" class="com.cdtax.service.impl.EmployeeService">
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 配置事务管理器,统一管理sessionFactory的事务 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="txManager"/>

</beans>

修改EmployeeService:

package com.cdtax.service.impl;

import java.io.Serializable;
import java.util.List;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;

import com.cdtax.domain.Employee;
import com.cdtax.service.interfaces.EmployeeServiceInter;

//这里配置@Tansactional用处是让spring的事务管理器接管该service的事务
//如果只想让事务管理器管理某个方法中的事务,那么就将注解加到方法上
@Transactional
public class EmployeeService implements EmployeeServiceInter
{

	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	public void addEmployee(Employee e)
	{
//		Session s = sessionFactory.openSession();
//		Transaction tx = s.beginTransaction();
//		s.save(e);
//		tx.commit();
		
		sessionFactory.getCurrentSession().save(e);
	}

	public List<Employee> showEmployee()
	{
		// TODO Auto-generated method stub
		return null;
	}

	public void updateEmployee(Employee e)
	{
		// TODO Auto-generated method stub

	}

	public void deleteEmployee(Serializable id)
	{
		// TODO Auto-generated method stub

	}

}

再次执行Test测试程序,执行成功,这样我们就不用在service中进行事务的处理了。

关于数据库、数据源、session工厂、事务管理器的关系看下图:

数据源与具体的数据库相关联,描述登录数据库必须的信息,用户名,密码,数据库地址等等,session工厂中引用了数据源,对特定数据库进行会话管理,事务管理器又引用了session工厂,也就间接应用了数据源,也就与特定数据库关联起来了,进行事务处理。

整个整合业务的结构图

12、配置我们的hibernate二级缓存[ ehcache / oscache ]

12.1)在applicationContext.xml中配置二级缓存

<!-- 配置会话工厂() -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<!-- 设置数据源 -->
	<property name="dataSource" ref="dataSource" /><!-- 应该想到类中有setDataSource()方法 -->
	<!-- 接管了haibernate的对象映射文件 -->
	<property name="mappingResources"><!-- 应该想到类中有setMappingResources()方法 -->
		<list>
			<value>com/cdtax/domain/Employee.hbm.xml</value>
		</list>
	</property>
	
	<property name="hibernateProperties">
		<value>
			hibernate.dialect=org.hibernate.dialect.MySQLDialect
			hibernate.hbm2ddl.auto=update
			hibernate.show_sql=true
			hibernate.format_sql=true
			<!-- 配置hibernate二级缓存 -->
			hibernate.cache.use_second_level_cache=true
        	hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
        	hibernate.generate_statistics=true
		</value>
	</property>
</bean>

12.2)在需要缓存的实体bean配置文件中加入缓存配置项Employee.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="com.cdtax.domain">
	<class name="Employee" table="employee">
	<cache usage="read-write"/>
	<!-- 主键策略 -->
	<id name="id" type="java.lang.Integer">
		<generator class="native" /> <!-- 主要有hilo sequence navtive increment uuid identity foreign -->
	</id>
 
 	<!-- 属性与列的映射写法之一 -->
	<property name="name" type="java.lang.String" column="name" length="64" />
	
	<!-- 属性与列的映射写法之一 -->
	<property name="email" type="java.lang.String">
		<column name="email" length="64"></column>
	</property>
	
	<property name="hiredate" type="java.util.Date">
		<column name="hiredate" />
	</property>	
	
	<property name="salary" type="java.lang.Float">
		<column name="salary" />
	</property>
	
	</class>
</hibernate-mapping>

usage说明了缓存的策略,

12.3)添加二级开发包

12.4)将我们的ehcache的配置文件ehcache.xml放到 src目录,

<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="java.io.tmpdir"/>


    <!--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="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        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.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

Ehcache默认的配置文件ehcache.xml(放在类路径下 src目录下即可)
    defaultCache节点为缺省的缓存策略
    maxElementsInMemory 内存中最大允许存在的对象数量
    eternal 设置缓存中的对象是否永远不过期
    overflowToDisk 把溢出的对象存放到硬盘上
    timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
    timeToLiveSeconds 指定缓存对象总的存活时间
    diskPersistent 当jvm结束是是否持久化对象
    diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间

12.5)测试二级缓存生效

13、整合struts

【上篇】
【下篇】

抱歉!评论已关闭.