Spring3+Struts2+JPA2.0

一、整合

  spring3版本: 3.1.1

  struts2版本:  2.3.4

  jpa2.0实现:  hibernate   4.1.1

  连接池:          BoneCP      0.7.1   (要求JDK6以上,应用服务器也需要保证JDK6以上)

  缓存:           ehcache     2.5.2

1、在MyEclipse下建立一个Web Project,把相应的jar到放到WEB-INF\lib目录中

  所需的jar:

  antlr-2.7.7.jar
  aopalliance-1.0.jar
  aspectjrt.jar
  aspectjweaver.jar
  bonecp-0.7.1.RELEASE.jar
  bonecp-provider-0.7.1-rc2.jar
  bonecp-spring-0.7.1-rc1.jar
  cglib-nodep-2.2.jar
  commons-fileupload-1.2.2.jar
  commons-io-2.0.1.jar
  commons-lang3-3.1.jar
  commons-logging-1.1.1.jar
  dom4j-1.6.1.jar
  ehcache-core-2.5.2.jar

     ehcache-spring-annotations-1.2.0.jar

  freemarker-2.3.19.jar

  guava-12.0.jar
  hibernate-commons-annotations-4.0.1.Final.jar
  hibernate-core-4.1.1.Final.jar
  hibernate-entitymanager-4.1.1.Final.jar
  hibernate-jpa-2.0-api-1.0.1.Final.jar
  javassist-3.15.0-GA.jar
  jboss-logging-3.1.0.GA.jar
  jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  log4j-1.2.17.jar
  mysql-connector-java-5.1.6-bin.jar
  ognl-3.0.5.jar
  org.springframework.aop-3.1.1.RELEASE.jar
  org.springframework.asm-3.1.1.RELEASE.jar
  org.springframework.aspects-3.1.1.RELEASE.jar
  org.springframework.beans-3.1.1.RELEASE.jar
  org.springframework.context-3.1.1.RELEASE.jar
  org.springframework.context.support-3.1.1.RELEASE.jar
  org.springframework.core-3.1.1.RELEASE.jar
  org.springframework.expression-3.1.1.RELEASE.jar
  org.springframework.jdbc-3.1.1.RELEASE.jar
  org.springframework.jms-3.1.1.RELEASE.jar
  org.springframework.orm-3.1.1.RELEASE.jar
  org.springframework.oxm-3.1.1.RELEASE.jar
  org.springframework.test-3.1.1.RELEASE.jar
  org.springframework.transaction-3.1.1.RELEASE.jar
  org.springframework.web-3.1.1.RELEASE.jar
  slf4j-api-1.6.1.jar
  slf4j-log4j12-1.6.1.jar
  struts2-core-2.3.4.jar
  struts2-spring-plugin-2.3.4.jar
  xwork-core-2.3.4.jar

 

2、JPA2.0的配置

  在src目录下建立一个名为META-INF的文件夹,在META-INF下建立一个名为persistence.xml的文件。

  在persistence.xml文件中,JPA和BoneCP连接池进行了整合。

  persistence.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
            http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
            
    <!-- 在使用容器管理的多数据源的情况下使用jta,不能使用RESOURCE-LOCAL选项 -->
    <persistence-unit name="APP_JPA" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>  
             <properties>
                 
                 <property name="javax.persistence.validation.mode" value="none"/>
                 <!-- 
                         如果是hibernte3,使用
                         <property name="hibernate.connection.provider_class" value="com.jolbox.bonecp.provider.BoneCPConnectionProvider"/> 
                  -->
                  <!--hibernte4使用  -->
                 <property name="hibernate.service.jdbc.connections.spi.provider_class" value="com.jolbox.bonecp.provider.BoneCPConnectionProvider"/> 
                
                <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> 
                <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> 
                <property name="hibernate.connection.username" value="root"/> 
                <property name="hibernate.connection.password" value="root"/> 
                <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring_struts_jpa?useUnicode=true&amp;characterEncoding=UTF-8"/> 
                <property name="hibernate.max_fetch_depth" value="3"/> 
                <property name="hibernate.hbm2ddl.auto" value="update"/> 
                <property name="hibernate.jdbc.fetch_size" value="18"/> 
                <property name="hibernate.jdbc.batch_size" value="10"/> 
                <property name="hibernate.show_sql" value="true"/> 
                <property name="hibernate.format_sql" value="true"/> 
                
                
                <!-- BoneCP参数设置 --> 
                
                <!-- 设置分区个数.这个参数默认为1,建议3-4(根据特定应用程序而定) --> 
                <property name="bonecp.partitionCount" value="3"/> 
                
                <!-- 设置每个分区含有connection最大个数.这个参数默认为2.如果小于2,BoneCP将设置为50. 
                        比如:partitionCount设置为3,maxConnectionPerPartition设置为5,你就会拥有总共15个connection.--> 
                <property name="bonecp.maxConnectionsPerPartition" value="20"/> 
                
                <!-- 设置每个分区含有连接最大小个数.这个参数默认为0 --> 
                <property name="bonecp.minConnectionsPerPartition" value="10"/> 
                
                <!-- 设置分区中的连接增长数量.这个参数默认为1 --> 
                <property name="bonecp.acquireIncrement" value="5"/> 
                
                <!-- 设置连接池阀值.这个参数默认为20.如果小于0或是大于100,BoneCP将设置为20.
                        连接池为每个分区至少维持20%数量的可用connection --> 
                <property name="bonecp.poolAvailabilityThreshold" value="20"/> 
                
                <!-- 设置connection助手线程个数.这个参数默认为3.如果小于0,BoneCP将设置为3. --> 
                <property name="bonecp.releaseHelperThreads" value="3"/>
                
                <!-- 设置connection的空闲存活时间.这个参数默认为60,单位:分钟.设置为0该功能失效. 
                        通过ConnectionTesterThread观察每个分区中的connection,如果这个connection距离最
                        后使用的时间大于这个参数就会被清除 --> 
                <property name="bonecp.idleMaxAge" value="240"/> 
                
                <!-- 设置测试connection的间隔时间.这个参数默认为240,单位:分钟.设置为0该功能失效. 
                        通过ConnectionTesterThread观察每个分区中的connection, 如果这个connection距离最后
                        使用的时间大于这个参数并且距离上一次测试的时间大于这个参数就会向数据库发送一条测试语句,
                        如果执行失败则将这个connection清除. --> 
                <property name="bonecp.idleConnectionTestPeriod" value="60"/> 
                
                <!-- 设置statement助手线程个数.这个参数默认为3.如果小于0,BoneCP将设置为3. --> 
                <property name="bonecp.statementsCacheSize" value="20"/> 
        </properties>
        
    </persistence-unit>
</persistence>

3、Struts2的配置

  在src目录下建立一个struts.xml文件。

  struts.xml文件内容:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.objectFactory" value="spring" />
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.action.extension" value="action" />
  

    <package name="default" namespace="/" extends="struts-default">
        
        
    </package>
    <!-- Add packages here -->
</struts>

  

4、ehcache缓存配置

  在src目录下建立名为ehcache.xml的文件。

  ehcache.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

   <!--  <diskStore path="java.io.tmpdir"/> -->
   
   <!-- 配置缓存文件存放路径 -->
   <diskStore path="E:/cachetmpdir" />

   <!--   
        
        1.必须要有的属性:   
        
        name: cache的名字,用来识别不同的cache,必须惟一。   
        
        maxElementsInMemory: 内存管理的缓存元素数量最大限值。   
        
        maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。   
        
        eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。   
        
        overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。   
        
        2.下面是一些可选属性:   
        
        timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。   
        
        timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。   
        
        diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。   
        
        diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。   
        
        diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。   
        
        memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用  
        
    -->
   

  <defaultCache maxElementsInMemory="10000"
                    eternal="false"
                    timeToIdleSeconds="120" 
                    timeToLiveSeconds="120" 
                    overflowToDisk="true"
                    maxElementsOnDisk="10000000" 
                    diskPersistent="false"
                    diskExpiryThreadIntervalSeconds="120" 
                    memoryStoreEvictionPolicy="LRU" />

  <cache name="userCache"
      memoryStoreEvictionPolicy="LRU"
      eternal="false"
      maxElementsInMemory="20"
      overflowToDisk="false"
      diskPersistent="false" />


</ehcache>

5、Spring的配置

  spring管理JPA的事务、struts2的action。

  在WEB-INF目录下建立一个名为applicationContext.xml的文件。

  applicationContext.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"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:p="http://www.springframework.org/schema/p"  
            xmlns:cache="http://www.springframework.org/schema/cache"  
               xsi:schemaLocation="
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                    http://www.springframework.org/schema/context      
                       http://www.springframework.org/schema/context/spring-context-3.1.xsd
                       http://www.springframework.org/schema/cache 
                     http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">  
        
      <!-- 定义组件扫描,配置需要扫描的包-->
      <context:component-scan base-package="cn.luxh.app" /> 
    
      <!-- 定义实体管理器工厂 -->
      <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
                   <property name="persistenceUnitName" value="APP_JPA"/>
      </bean>
 
      <!-- 配置事务管理器 -->  
      <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">  
           <property name="entityManagerFactory" ref="entityManagerFactory" />  
      </bean>  
      
      <!-- 启用 annotation事务--> 
      <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 启用缓存注解功能 -->
       <ehcache:annotation-driven cache-manager="ehCacheManager" />  
     
       
       <!-- cacheManager工厂类,指定ehcache.xml的位置 -->    
       <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
              p:configLocation="classpath:/ehcache.xml"/>
</beans>

6、web.xml配置

  web.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
          <display-name>app</display-name>
          
          <!-- 配置Log4j -->
          <context-param>
                <param-name>webAppRootKey</param-name>
                <param-value>spring_struts_jpa.root</param-value>
          </context-param>
          <context-param>
                <param-name>log4jConfigLocation</param-name>
                <param-value>classpath:log4j.properties</param-value>
          </context-param>
          <listener>
                <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
          </listener>
          
          <!-- 配置编码过滤器 -->
          <filter>
                <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
                <url-pattern>/*</url-pattern>
          </filter-mapping>
          
          <!-- 加载Spring监听器 -->
          <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
          <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/applicationContext.xml</param-value>
          </context-param>
          
         <!--配置缓存清除监听器  处理由 JavaBean Introspector功能而引起的缓存泄露 -->
          <listener>
                  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
          </listener>
          
          <!--配置Struts2过滤器 -->
          <filter>
                <filter-name>struts2</filter-name>
                <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
          </filter>
          <filter-mapping>
                <filter-name>struts2</filter-name>
                <url-pattern>/*</url-pattern>
          </filter-mapping>
          
          
          <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
          
</web-app>

7、ok,Spring3+Struts2+JPA2.0整合完毕。


   

二、使用

1、实体类。

@Entity
@Table(name="t_user")
public class User implements Serializable{
    private static final long serialVersionUID = -3647733101497063659L;

    @Id
    @GeneratedValue
    private Long id;
    
    /**账号*/
    @Column(length=32)
    private String account;
    
    /**密码*/
    @Column(length=32)
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
}

  

2、DAO

  1)写一个BaseDao接口和BaseDaoImpl实现类,这里是示例,只写两个方法。

  @Repository用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean。

  BaseDao.java:

public interface BaseDao {
    
    /**
     * 新增实体
     * @param entity  要新增的实体
     */
    public void save(Object entity);
    
        
    /**
     * 根据主键查询
     * @param <T>
     * @param clazz  实体类的Class
     * @param id     主键
     * @return
     */
    public <T> T getById(Class<T> clazz,Object id);

}

  BaseDaoImpl.java:

@Repository(value="baseDao")
public class BaseDaoImpl implements BaseDao {
    
    
    @PersistenceContext 
    protected EntityManager em;

    public void save(Object entity) {
        em.persist(entity);
    }

    public <T> T getById(Class<T> clazz, Object id) {
        return em.find(clazz, id);
    }
}

  2)写一个用户数据访问的UserDao接口和UserDaoImpl实现类。

  UserDao.java:

public interface UserDao extends BaseDao{

}

  UserDaoImpl.java:

@Repository(value="userDao")
public class UserDaoImpl extends BaseDaoImpl implements UserDao {

}


3、Service

  1)BaseService接口。

public interface BaseService {
    /**
     * 新增实体
     * @param entity
     */
     public void save(Object entity);

    /**
     * 根据主键查询
     * @param <T>
     * @param clazz  实体类的Class
     * @param id     主键
     * @return
     */
    public <T> T getById(Class<T> clazz,Object id);

}

  2)用户管理服务接口和实现类。

  UserService.java:

public interface UserService extends BaseService {
    
}

  UserServiceImpl.java:

@Service(value="userService")
public class UserServiceImpl implements UserService {

    @Resource(name="userDao")
    private UserDao userDao;

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    @TriggersRemove(cacheName="userCache",removeAll=true)
    public void save(Object entity) {
        userDao.save(entity);
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED,readOnly=true)
    @Cacheable(cacheName="userCache")
    public <User> User getById(Class<User> clazz, Object id) {
        return userDao.getById(clazz, id);
    }

}

  @Service(value="userService")  用于将业务层的类标识为 Spring Bean。

  @Resource(name="userDao")  根据名字注入资源

  @Transactional(propagation=Propagation.REQUIRED)  注解式事务

  @Cacheable(cacheName="userCache")     注解式缓存,将方法的返回值加入到名称为userCache的缓存中

      @TriggersRemove(cacheName="userCache",removeAll=true)        注解式缓存,清除缓存名称为userCache缓存

4、缓存文件配置

  在ehcache.xml中配置userCache缓存。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

   <!--  <diskStore path="java.io.tmpdir"/> -->
   
   <!-- 配置缓存文件存放路径 -->
   <diskStore path="E:/cachetmpdir" />

   <!--   
        
        1.必须要有的属性:   
        
        name: cache的名字,用来识别不同的cache,必须惟一。   
        
        maxElementsInMemory: 内存管理的缓存元素数量最大限值。   
        
        maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。   
        
        eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。   
        
        overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。   
        
        2.下面是一些可选属性:   
        
        timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。   
        
        timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。   
        
        diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。   
        
        diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。   
        
        diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。   
        
        memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。
                                               First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用  
        
    -->
   

  <defaultCache maxElementsInMemory="10000"
                    eternal="false"
                    timeToIdleSeconds="120" 
                    timeToLiveSeconds="120" 
                    overflowToDisk="true"
                    maxElementsOnDisk="10000000" 
                    diskPersistent="false"
                    diskExpiryThreadIntervalSeconds="120" 
                    memoryStoreEvictionPolicy="LRU" />
                    
    <!-- User cache -->
    <cache name="userCache"
          maxElementsInMemory="10000"
          maxElementsOnDisk="1000"
          eternal="false"
          overflowToDisk="true"
          diskSpoolBufferSizeMB="20" 
          timeToIdleSeconds="300"
          timeToLiveSeconds="600" 
          memoryStoreEvictionPolicy="LFU" />
          
</ehcache>


5、Action

  UserAction.java: 

@Controller
@Scope("prototype")
public class UserAction extends ActionSupport{

    @Resource(name="userService")
    private UserService userService;

    /**
     * 保存用户
     */
    public String saveUser() {
        User user = new User();
        user.setAccount("admin");
        user.setPassword("admin");
        userService.saveEntity(user);
        return SUCCESS;
    }

    /**
     * 根据ID查找用户
     */
    public String findUserById() {
        long id = 1L;
        User user = userService.getById(User.class, id);
        return SUCCESS;
    }


}

  @Controller用于将控制层的类标识为 Spring Bean。

6、在struts.xml添加action的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.objectFactory" value="spring" />
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.action.extension" value="action" />
  

    <package name="default" namespace="/" extends="struts-default">
        <!-- 保存用户 -->
         <action name="saveUser" class="userAction" method="saveUser">
            <result>/WEB-INF/page/user/userList.jsp</result>
        </action>
        
        <!-- 根据ID查找用户 -->
         <action name="findUserById" class="userAction" method="findUserById">
            <result>/WEB-INF/page/user/userDetail.jsp</result>
        </action>
        
    </package>
    <!-- Add packages here -->
</struts>

 

7、spring配置文件applicationContext.xml不再需要任何额外的配置。


8、ok,简单的使用完毕。

  

  

  

原文地址:https://www.cnblogs.com/luxh/p/2611987.html